babylon.max.js 4.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216982179821898219982209822198222982239822498225982269822798228982299823098231982329823398234982359823698237982389823998240982419824298243982449824598246982479824898249982509825198252982539825498255982569825798258982599826098261
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. var scene = this._mesh.getScene();
  101. for (var index = 0; index < scene.meshes.length; index++) {
  102. var otherMesh = scene.meshes[index];
  103. if (!otherMesh.material) {
  104. continue;
  105. }
  106. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  107. continue;
  108. }
  109. if (otherMesh.material.getEffect() === effect) {
  110. otherMesh.computeBonesUsingShaders = false;
  111. }
  112. else {
  113. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  114. var subMesh = _a[_i];
  115. var subMeshEffect = subMesh.effect;
  116. if (subMeshEffect === effect) {
  117. otherMesh.computeBonesUsingShaders = false;
  118. break;
  119. }
  120. }
  121. }
  122. }
  123. }
  124. else {
  125. var currentFallbacks = this._defines[this._currentRank];
  126. if (currentFallbacks) {
  127. for (var index = 0; index < currentFallbacks.length; index++) {
  128. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  129. }
  130. }
  131. this._currentRank++;
  132. }
  133. return currentDefines;
  134. };
  135. return EffectFallbacks;
  136. }());
  137. BABYLON.EffectFallbacks = EffectFallbacks;
  138. /**
  139. * Options to be used when creating an effect.
  140. */
  141. var EffectCreationOptions = /** @class */ (function () {
  142. function EffectCreationOptions() {
  143. }
  144. return EffectCreationOptions;
  145. }());
  146. BABYLON.EffectCreationOptions = EffectCreationOptions;
  147. /**
  148. * Effect containing vertex and fragment shader that can be executed on an object.
  149. */
  150. var Effect = /** @class */ (function () {
  151. /**
  152. * Instantiates an effect.
  153. * An effect can be used to create/manage/execute vertex and fragment shaders.
  154. * @param baseName Name of the effect.
  155. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  156. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  157. * @param samplers List of sampler variables that will be passed to the shader.
  158. * @param engine Engine to be used to render the effect
  159. * @param defines Define statements to be added to the shader.
  160. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  161. * @param onCompiled Callback that will be called when the shader is compiled.
  162. * @param onError Callback that will be called if an error occurs during shader compilation.
  163. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  164. */
  165. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  166. if (samplers === void 0) { samplers = null; }
  167. if (defines === void 0) { defines = null; }
  168. if (fallbacks === void 0) { fallbacks = null; }
  169. if (onCompiled === void 0) { onCompiled = null; }
  170. if (onError === void 0) { onError = null; }
  171. var _this = this;
  172. /**
  173. * Unique ID of the effect.
  174. */
  175. this.uniqueId = 0;
  176. /**
  177. * Observable that will be called when the shader is compiled.
  178. */
  179. this.onCompileObservable = new BABYLON.Observable();
  180. /**
  181. * Observable that will be called if an error occurs during shader compilation.
  182. */
  183. this.onErrorObservable = new BABYLON.Observable();
  184. /**
  185. * Observable that will be called when effect is bound.
  186. */
  187. this.onBindObservable = new BABYLON.Observable();
  188. this._uniformBuffersNames = {};
  189. this._isReady = false;
  190. this._compilationError = "";
  191. this.name = baseName;
  192. if (attributesNamesOrOptions.attributes) {
  193. var options = attributesNamesOrOptions;
  194. this._engine = uniformsNamesOrEngine;
  195. this._attributesNames = options.attributes;
  196. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  197. this._samplers = options.samplers.slice();
  198. this.defines = options.defines;
  199. this.onError = options.onError;
  200. this.onCompiled = options.onCompiled;
  201. this._fallbacks = options.fallbacks;
  202. this._indexParameters = options.indexParameters;
  203. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  204. if (options.uniformBuffersNames) {
  205. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  206. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  207. }
  208. }
  209. }
  210. else {
  211. this._engine = engine;
  212. this.defines = defines;
  213. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  214. this._samplers = samplers ? samplers.slice() : [];
  215. this._attributesNames = attributesNamesOrOptions;
  216. this.onError = onError;
  217. this.onCompiled = onCompiled;
  218. this._indexParameters = indexParameters;
  219. this._fallbacks = fallbacks;
  220. }
  221. this.uniqueId = Effect._uniqueIdSeed++;
  222. var vertexSource;
  223. var fragmentSource;
  224. if (baseName.vertexElement) {
  225. vertexSource = document.getElementById(baseName.vertexElement);
  226. if (!vertexSource) {
  227. vertexSource = baseName.vertexElement;
  228. }
  229. }
  230. else {
  231. vertexSource = baseName.vertex || baseName;
  232. }
  233. if (baseName.fragmentElement) {
  234. fragmentSource = document.getElementById(baseName.fragmentElement);
  235. if (!fragmentSource) {
  236. fragmentSource = baseName.fragmentElement;
  237. }
  238. }
  239. else {
  240. fragmentSource = baseName.fragment || baseName;
  241. }
  242. this._loadVertexShader(vertexSource, function (vertexCode) {
  243. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  244. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  245. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  246. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  247. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  248. if (baseName) {
  249. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  250. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  251. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  252. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  253. }
  254. else {
  255. _this._vertexSourceCode = migratedVertexCode;
  256. _this._fragmentSourceCode = migratedFragmentCode;
  257. }
  258. _this._prepareEffect();
  259. });
  260. });
  261. });
  262. });
  263. });
  264. });
  265. }
  266. Object.defineProperty(Effect.prototype, "key", {
  267. /**
  268. * Unique key for this effect
  269. */
  270. get: function () {
  271. return this._key;
  272. },
  273. enumerable: true,
  274. configurable: true
  275. });
  276. /**
  277. * If the effect has been compiled and prepared.
  278. * @returns if the effect is compiled and prepared.
  279. */
  280. Effect.prototype.isReady = function () {
  281. return this._isReady;
  282. };
  283. /**
  284. * The engine the effect was initialized with.
  285. * @returns the engine.
  286. */
  287. Effect.prototype.getEngine = function () {
  288. return this._engine;
  289. };
  290. /**
  291. * The compiled webGL program for the effect
  292. * @returns the webGL program.
  293. */
  294. Effect.prototype.getProgram = function () {
  295. return this._program;
  296. };
  297. /**
  298. * The set of names of attribute variables for the shader.
  299. * @returns An array of attribute names.
  300. */
  301. Effect.prototype.getAttributesNames = function () {
  302. return this._attributesNames;
  303. };
  304. /**
  305. * Returns the attribute at the given index.
  306. * @param index The index of the attribute.
  307. * @returns The location of the attribute.
  308. */
  309. Effect.prototype.getAttributeLocation = function (index) {
  310. return this._attributes[index];
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param name of the attribute to look up.
  315. * @returns the attribute location.
  316. */
  317. Effect.prototype.getAttributeLocationByName = function (name) {
  318. var index = this._attributesNames.indexOf(name);
  319. return this._attributes[index];
  320. };
  321. /**
  322. * The number of attributes.
  323. * @returns the numnber of attributes.
  324. */
  325. Effect.prototype.getAttributesCount = function () {
  326. return this._attributes.length;
  327. };
  328. /**
  329. * Gets the index of a uniform variable.
  330. * @param uniformName of the uniform to look up.
  331. * @returns the index.
  332. */
  333. Effect.prototype.getUniformIndex = function (uniformName) {
  334. return this._uniformsNames.indexOf(uniformName);
  335. };
  336. /**
  337. * Returns the attribute based on the name of the variable.
  338. * @param uniformName of the uniform to look up.
  339. * @returns the location of the uniform.
  340. */
  341. Effect.prototype.getUniform = function (uniformName) {
  342. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  343. };
  344. /**
  345. * Returns an array of sampler variable names
  346. * @returns The array of sampler variable neames.
  347. */
  348. Effect.prototype.getSamplers = function () {
  349. return this._samplers;
  350. };
  351. /**
  352. * The error from the last compilation.
  353. * @returns the error string.
  354. */
  355. Effect.prototype.getCompilationError = function () {
  356. return this._compilationError;
  357. };
  358. /**
  359. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  360. * @param func The callback to be used.
  361. */
  362. Effect.prototype.executeWhenCompiled = function (func) {
  363. if (this.isReady()) {
  364. func(this);
  365. return;
  366. }
  367. this.onCompileObservable.add(function (effect) {
  368. func(effect);
  369. });
  370. };
  371. /** @hidden */
  372. Effect.prototype._loadVertexShader = function (vertex, callback) {
  373. if (BABYLON.Tools.IsWindowObjectExist()) {
  374. // DOM element ?
  375. if (vertex instanceof HTMLElement) {
  376. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  377. callback(vertexCode);
  378. return;
  379. }
  380. }
  381. // Base64 encoded ?
  382. if (vertex.substr(0, 7) === "base64:") {
  383. var vertexBinary = window.atob(vertex.substr(7));
  384. callback(vertexBinary);
  385. return;
  386. }
  387. // Is in local store ?
  388. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  389. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  390. return;
  391. }
  392. var vertexShaderUrl;
  393. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  394. vertexShaderUrl = vertex;
  395. }
  396. else {
  397. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  398. }
  399. // Vertex shader
  400. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  401. };
  402. /** @hidden */
  403. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  404. if (BABYLON.Tools.IsWindowObjectExist()) {
  405. // DOM element ?
  406. if (fragment instanceof HTMLElement) {
  407. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  408. callback(fragmentCode);
  409. return;
  410. }
  411. }
  412. // Base64 encoded ?
  413. if (fragment.substr(0, 7) === "base64:") {
  414. var fragmentBinary = window.atob(fragment.substr(7));
  415. callback(fragmentBinary);
  416. return;
  417. }
  418. // Is in local store ?
  419. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  420. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  421. return;
  422. }
  423. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  424. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  425. return;
  426. }
  427. var fragmentShaderUrl;
  428. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  429. fragmentShaderUrl = fragment;
  430. }
  431. else {
  432. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  433. }
  434. // Fragment shader
  435. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  436. };
  437. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  438. // Rebuild shaders source code
  439. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  440. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  441. vertexCode = prefix + vertexCode;
  442. fragmentCode = prefix + fragmentCode;
  443. // Number lines of shaders source code
  444. var i = 2;
  445. var regex = /\n/gm;
  446. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  447. i = 2;
  448. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  449. // Dump shaders name and formatted source code
  450. if (this.name.vertexElement) {
  451. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  452. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  453. }
  454. else if (this.name.vertex) {
  455. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  456. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  457. }
  458. else {
  459. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  460. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  461. }
  462. };
  463. ;
  464. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  465. var preparedSourceCode = this._processPrecision(sourceCode);
  466. if (this._engine.webGLVersion == 1) {
  467. callback(preparedSourceCode);
  468. return;
  469. }
  470. // Already converted
  471. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  472. callback(preparedSourceCode.replace("#version 300 es", ""));
  473. return;
  474. }
  475. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  476. // Remove extensions
  477. // #extension GL_OES_standard_derivatives : enable
  478. // #extension GL_EXT_shader_texture_lod : enable
  479. // #extension GL_EXT_frag_depth : enable
  480. // #extension GL_EXT_draw_buffers : require
  481. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  482. var result = preparedSourceCode.replace(regex, "");
  483. // Migrate to GLSL v300
  484. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  485. result = result.replace(/attribute[ \t]/g, "in ");
  486. result = result.replace(/[ \t]attribute/g, " in");
  487. if (isFragment) {
  488. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  489. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  490. result = result.replace(/texture2D\s*\(/g, "texture(");
  491. result = result.replace(/textureCube\s*\(/g, "texture(");
  492. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  493. result = result.replace(/gl_FragColor/g, "glFragColor");
  494. result = result.replace(/gl_FragData/g, "glFragData");
  495. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  496. }
  497. callback(result);
  498. };
  499. Effect.prototype._processIncludes = function (sourceCode, callback) {
  500. var _this = this;
  501. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  502. var match = regex.exec(sourceCode);
  503. var returnValue = new String(sourceCode);
  504. while (match != null) {
  505. var includeFile = match[1];
  506. // Uniform declaration
  507. if (includeFile.indexOf("__decl__") !== -1) {
  508. includeFile = includeFile.replace(/__decl__/, "");
  509. if (this._engine.supportsUniformBuffers) {
  510. includeFile = includeFile.replace(/Vertex/, "Ubo");
  511. includeFile = includeFile.replace(/Fragment/, "Ubo");
  512. }
  513. includeFile = includeFile + "Declaration";
  514. }
  515. if (Effect.IncludesShadersStore[includeFile]) {
  516. // Substitution
  517. var includeContent = Effect.IncludesShadersStore[includeFile];
  518. if (match[2]) {
  519. var splits = match[3].split(",");
  520. for (var index = 0; index < splits.length; index += 2) {
  521. var source = new RegExp(splits[index], "g");
  522. var dest = splits[index + 1];
  523. includeContent = includeContent.replace(source, dest);
  524. }
  525. }
  526. if (match[4]) {
  527. var indexString = match[5];
  528. if (indexString.indexOf("..") !== -1) {
  529. var indexSplits = indexString.split("..");
  530. var minIndex = parseInt(indexSplits[0]);
  531. var maxIndex = parseInt(indexSplits[1]);
  532. var sourceIncludeContent = includeContent.slice(0);
  533. includeContent = "";
  534. if (isNaN(maxIndex)) {
  535. maxIndex = this._indexParameters[indexSplits[1]];
  536. }
  537. for (var i = minIndex; i < maxIndex; i++) {
  538. if (!this._engine.supportsUniformBuffers) {
  539. // Ubo replacement
  540. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  541. return p1 + "{X}";
  542. });
  543. }
  544. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  545. }
  546. }
  547. else {
  548. if (!this._engine.supportsUniformBuffers) {
  549. // Ubo replacement
  550. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  551. return p1 + "{X}";
  552. });
  553. }
  554. includeContent = includeContent.replace(/\{X\}/g, indexString);
  555. }
  556. }
  557. // Replace
  558. returnValue = returnValue.replace(match[0], includeContent);
  559. }
  560. else {
  561. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  562. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  563. Effect.IncludesShadersStore[includeFile] = fileContent;
  564. _this._processIncludes(returnValue, callback);
  565. });
  566. return;
  567. }
  568. match = regex.exec(sourceCode);
  569. }
  570. callback(returnValue);
  571. };
  572. Effect.prototype._processPrecision = function (source) {
  573. if (source.indexOf("precision highp float") === -1) {
  574. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  575. source = "precision mediump float;\n" + source;
  576. }
  577. else {
  578. source = "precision highp float;\n" + source;
  579. }
  580. }
  581. else {
  582. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  583. source = source.replace("precision highp float", "precision mediump float");
  584. }
  585. }
  586. return source;
  587. };
  588. /**
  589. * Recompiles the webGL program
  590. * @param vertexSourceCode The source code for the vertex shader.
  591. * @param fragmentSourceCode The source code for the fragment shader.
  592. * @param onCompiled Callback called when completed.
  593. * @param onError Callback called on error.
  594. */
  595. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  596. var _this = this;
  597. this._isReady = false;
  598. this._vertexSourceCodeOverride = vertexSourceCode;
  599. this._fragmentSourceCodeOverride = fragmentSourceCode;
  600. this.onError = function (effect, error) {
  601. if (onError) {
  602. onError(error);
  603. }
  604. };
  605. this.onCompiled = function () {
  606. var scenes = _this.getEngine().scenes;
  607. for (var i = 0; i < scenes.length; i++) {
  608. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  609. }
  610. if (onCompiled) {
  611. onCompiled(_this._program);
  612. }
  613. };
  614. this._fallbacks = null;
  615. this._prepareEffect();
  616. };
  617. /**
  618. * Gets the uniform locations of the the specified variable names
  619. * @param names THe names of the variables to lookup.
  620. * @returns Array of locations in the same order as variable names.
  621. */
  622. Effect.prototype.getSpecificUniformLocations = function (names) {
  623. var engine = this._engine;
  624. return engine.getUniforms(this._program, names);
  625. };
  626. /**
  627. * Prepares the effect
  628. */
  629. Effect.prototype._prepareEffect = function () {
  630. var attributesNames = this._attributesNames;
  631. var defines = this.defines;
  632. var fallbacks = this._fallbacks;
  633. this._valueCache = {};
  634. var previousProgram = this._program;
  635. try {
  636. var engine = this._engine;
  637. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  638. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  639. }
  640. else {
  641. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  642. }
  643. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  644. if (engine.supportsUniformBuffers) {
  645. for (var name in this._uniformBuffersNames) {
  646. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  647. }
  648. }
  649. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  650. this._attributes = engine.getAttributes(this._program, attributesNames);
  651. var index;
  652. for (index = 0; index < this._samplers.length; index++) {
  653. var sampler = this.getUniform(this._samplers[index]);
  654. if (sampler == null) {
  655. this._samplers.splice(index, 1);
  656. index--;
  657. }
  658. }
  659. engine.bindSamplers(this);
  660. this._compilationError = "";
  661. this._isReady = true;
  662. if (this.onCompiled) {
  663. this.onCompiled(this);
  664. }
  665. this.onCompileObservable.notifyObservers(this);
  666. this.onCompileObservable.clear();
  667. // Unbind mesh reference in fallbacks
  668. if (this._fallbacks) {
  669. this._fallbacks.unBindMesh();
  670. }
  671. if (previousProgram) {
  672. this.getEngine()._deleteProgram(previousProgram);
  673. }
  674. }
  675. catch (e) {
  676. this._compilationError = e.message;
  677. // Let's go through fallbacks then
  678. BABYLON.Tools.Error("Unable to compile effect:");
  679. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  680. return " " + uniform;
  681. }));
  682. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  683. return " " + attribute;
  684. }));
  685. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  686. BABYLON.Tools.Error("Error: " + this._compilationError);
  687. if (previousProgram) {
  688. this._program = previousProgram;
  689. this._isReady = true;
  690. if (this.onError) {
  691. this.onError(this, this._compilationError);
  692. }
  693. this.onErrorObservable.notifyObservers(this);
  694. }
  695. if (fallbacks && fallbacks.isMoreFallbacks) {
  696. BABYLON.Tools.Error("Trying next fallback.");
  697. this.defines = fallbacks.reduce(this.defines, this);
  698. this._prepareEffect();
  699. }
  700. else { // Sorry we did everything we can
  701. if (this.onError) {
  702. this.onError(this, this._compilationError);
  703. }
  704. this.onErrorObservable.notifyObservers(this);
  705. this.onErrorObservable.clear();
  706. // Unbind mesh reference in fallbacks
  707. if (this._fallbacks) {
  708. this._fallbacks.unBindMesh();
  709. }
  710. }
  711. }
  712. };
  713. Object.defineProperty(Effect.prototype, "isSupported", {
  714. /**
  715. * Checks if the effect is supported. (Must be called after compilation)
  716. */
  717. get: function () {
  718. return this._compilationError === "";
  719. },
  720. enumerable: true,
  721. configurable: true
  722. });
  723. /**
  724. * Binds a texture to the engine to be used as output of the shader.
  725. * @param channel Name of the output variable.
  726. * @param texture Texture to bind.
  727. */
  728. Effect.prototype._bindTexture = function (channel, texture) {
  729. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  730. };
  731. /**
  732. * Sets a texture on the engine to be used in the shader.
  733. * @param channel Name of the sampler variable.
  734. * @param texture Texture to set.
  735. */
  736. Effect.prototype.setTexture = function (channel, texture) {
  737. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  738. };
  739. /**
  740. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  741. * @param channel Name of the sampler variable.
  742. * @param texture Texture to set.
  743. */
  744. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  745. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  746. };
  747. /**
  748. * Sets an array of textures on the engine to be used in the shader.
  749. * @param channel Name of the variable.
  750. * @param textures Textures to set.
  751. */
  752. Effect.prototype.setTextureArray = function (channel, textures) {
  753. if (this._samplers.indexOf(channel + "Ex") === -1) {
  754. var initialPos = this._samplers.indexOf(channel);
  755. for (var index = 1; index < textures.length; index++) {
  756. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  757. }
  758. }
  759. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  760. };
  761. /**
  762. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  763. * @param channel Name of the sampler variable.
  764. * @param postProcess Post process to get the input texture from.
  765. */
  766. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  767. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  768. };
  769. /**
  770. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  771. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  772. * @param channel Name of the sampler variable.
  773. * @param postProcess Post process to get the output texture from.
  774. */
  775. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  776. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  777. };
  778. /** @hidden */
  779. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  780. var cache = this._valueCache[uniformName];
  781. var flag = matrix.updateFlag;
  782. if (cache !== undefined && cache === flag) {
  783. return false;
  784. }
  785. this._valueCache[uniformName] = flag;
  786. return true;
  787. };
  788. /** @hidden */
  789. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  790. var cache = this._valueCache[uniformName];
  791. if (!cache) {
  792. cache = [x, y];
  793. this._valueCache[uniformName] = cache;
  794. return true;
  795. }
  796. var changed = false;
  797. if (cache[0] !== x) {
  798. cache[0] = x;
  799. changed = true;
  800. }
  801. if (cache[1] !== y) {
  802. cache[1] = y;
  803. changed = true;
  804. }
  805. return changed;
  806. };
  807. /** @hidden */
  808. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  809. var cache = this._valueCache[uniformName];
  810. if (!cache) {
  811. cache = [x, y, z];
  812. this._valueCache[uniformName] = cache;
  813. return true;
  814. }
  815. var changed = false;
  816. if (cache[0] !== x) {
  817. cache[0] = x;
  818. changed = true;
  819. }
  820. if (cache[1] !== y) {
  821. cache[1] = y;
  822. changed = true;
  823. }
  824. if (cache[2] !== z) {
  825. cache[2] = z;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /** @hidden */
  831. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  832. var cache = this._valueCache[uniformName];
  833. if (!cache) {
  834. cache = [x, y, z, w];
  835. this._valueCache[uniformName] = cache;
  836. return true;
  837. }
  838. var changed = false;
  839. if (cache[0] !== x) {
  840. cache[0] = x;
  841. changed = true;
  842. }
  843. if (cache[1] !== y) {
  844. cache[1] = y;
  845. changed = true;
  846. }
  847. if (cache[2] !== z) {
  848. cache[2] = z;
  849. changed = true;
  850. }
  851. if (cache[3] !== w) {
  852. cache[3] = w;
  853. changed = true;
  854. }
  855. return changed;
  856. };
  857. /**
  858. * Binds a buffer to a uniform.
  859. * @param buffer Buffer to bind.
  860. * @param name Name of the uniform variable to bind to.
  861. */
  862. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  863. var bufferName = this._uniformBuffersNames[name];
  864. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  865. return;
  866. }
  867. Effect._baseCache[bufferName] = buffer;
  868. this._engine.bindUniformBufferBase(buffer, bufferName);
  869. };
  870. /**
  871. * Binds block to a uniform.
  872. * @param blockName Name of the block to bind.
  873. * @param index Index to bind.
  874. */
  875. Effect.prototype.bindUniformBlock = function (blockName, index) {
  876. this._engine.bindUniformBlock(this._program, blockName, index);
  877. };
  878. /**
  879. * Sets an interger value on a uniform variable.
  880. * @param uniformName Name of the variable.
  881. * @param value Value to be set.
  882. * @returns this effect.
  883. */
  884. Effect.prototype.setInt = function (uniformName, value) {
  885. var cache = this._valueCache[uniformName];
  886. if (cache !== undefined && cache === value)
  887. return this;
  888. this._valueCache[uniformName] = value;
  889. this._engine.setInt(this.getUniform(uniformName), value);
  890. return this;
  891. };
  892. /**
  893. * Sets an int array on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param array array to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setIntArray = function (uniformName, array) {
  899. this._valueCache[uniformName] = null;
  900. this._engine.setIntArray(this.getUniform(uniformName), array);
  901. return this;
  902. };
  903. /**
  904. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  905. * @param uniformName Name of the variable.
  906. * @param array array to be set.
  907. * @returns this effect.
  908. */
  909. Effect.prototype.setIntArray2 = function (uniformName, array) {
  910. this._valueCache[uniformName] = null;
  911. this._engine.setIntArray2(this.getUniform(uniformName), array);
  912. return this;
  913. };
  914. /**
  915. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  916. * @param uniformName Name of the variable.
  917. * @param array array to be set.
  918. * @returns this effect.
  919. */
  920. Effect.prototype.setIntArray3 = function (uniformName, array) {
  921. this._valueCache[uniformName] = null;
  922. this._engine.setIntArray3(this.getUniform(uniformName), array);
  923. return this;
  924. };
  925. /**
  926. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  927. * @param uniformName Name of the variable.
  928. * @param array array to be set.
  929. * @returns this effect.
  930. */
  931. Effect.prototype.setIntArray4 = function (uniformName, array) {
  932. this._valueCache[uniformName] = null;
  933. this._engine.setIntArray4(this.getUniform(uniformName), array);
  934. return this;
  935. };
  936. /**
  937. * Sets an float array on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param array array to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setFloatArray = function (uniformName, array) {
  943. this._valueCache[uniformName] = null;
  944. this._engine.setFloatArray(this.getUniform(uniformName), array);
  945. return this;
  946. };
  947. /**
  948. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  949. * @param uniformName Name of the variable.
  950. * @param array array to be set.
  951. * @returns this effect.
  952. */
  953. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  954. this._valueCache[uniformName] = null;
  955. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  956. return this;
  957. };
  958. /**
  959. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  960. * @param uniformName Name of the variable.
  961. * @param array array to be set.
  962. * @returns this effect.
  963. */
  964. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  965. this._valueCache[uniformName] = null;
  966. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  967. return this;
  968. };
  969. /**
  970. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * Sets an array on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param array array to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setArray = function (uniformName, array) {
  987. this._valueCache[uniformName] = null;
  988. this._engine.setArray(this.getUniform(uniformName), array);
  989. return this;
  990. };
  991. /**
  992. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  993. * @param uniformName Name of the variable.
  994. * @param array array to be set.
  995. * @returns this effect.
  996. */
  997. Effect.prototype.setArray2 = function (uniformName, array) {
  998. this._valueCache[uniformName] = null;
  999. this._engine.setArray2(this.getUniform(uniformName), array);
  1000. return this;
  1001. };
  1002. /**
  1003. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1004. * @param uniformName Name of the variable.
  1005. * @param array array to be set.
  1006. * @returns this effect.
  1007. */
  1008. Effect.prototype.setArray3 = function (uniformName, array) {
  1009. this._valueCache[uniformName] = null;
  1010. this._engine.setArray3(this.getUniform(uniformName), array);
  1011. return this;
  1012. };
  1013. /**
  1014. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1015. * @param uniformName Name of the variable.
  1016. * @param array array to be set.
  1017. * @returns this effect.
  1018. */
  1019. Effect.prototype.setArray4 = function (uniformName, array) {
  1020. this._valueCache[uniformName] = null;
  1021. this._engine.setArray4(this.getUniform(uniformName), array);
  1022. return this;
  1023. };
  1024. /**
  1025. * Sets matrices on a uniform variable.
  1026. * @param uniformName Name of the variable.
  1027. * @param matrices matrices to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1031. if (!matrices) {
  1032. return this;
  1033. }
  1034. this._valueCache[uniformName] = null;
  1035. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets matrix on a uniform variable.
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1045. if (this._cacheMatrix(uniformName, matrix)) {
  1046. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1047. }
  1048. return this;
  1049. };
  1050. /**
  1051. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1052. * @param uniformName Name of the variable.
  1053. * @param matrix matrix to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1063. * @param uniformName Name of the variable.
  1064. * @param matrix matrix to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1068. this._valueCache[uniformName] = null;
  1069. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1070. return this;
  1071. };
  1072. /**
  1073. * Sets a float on a uniform variable.
  1074. * @param uniformName Name of the variable.
  1075. * @param value value to be set.
  1076. * @returns this effect.
  1077. */
  1078. Effect.prototype.setFloat = function (uniformName, value) {
  1079. var cache = this._valueCache[uniformName];
  1080. if (cache !== undefined && cache === value)
  1081. return this;
  1082. this._valueCache[uniformName] = value;
  1083. this._engine.setFloat(this.getUniform(uniformName), value);
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a boolean on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param bool value to be set.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setBool = function (uniformName, bool) {
  1093. var cache = this._valueCache[uniformName];
  1094. if (cache !== undefined && cache === bool)
  1095. return this;
  1096. this._valueCache[uniformName] = bool;
  1097. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a Vector2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param vector2 vector2 to be set.
  1104. * @returns this effect.
  1105. */
  1106. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1107. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1108. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1109. }
  1110. return this;
  1111. };
  1112. /**
  1113. * Sets a float2 on a uniform variable.
  1114. * @param uniformName Name of the variable.
  1115. * @param x First float in float2.
  1116. * @param y Second float in float2.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1120. if (this._cacheFloat2(uniformName, x, y)) {
  1121. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector3 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1132. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1133. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float3 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float3.
  1141. * @param y Second float in float3.
  1142. * @param z Third float in float3.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1146. if (this._cacheFloat3(uniformName, x, y, z)) {
  1147. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Vector4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param vector4 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1158. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1159. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a float4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param x First float in float4.
  1167. * @param y Second float in float4.
  1168. * @param z Third float in float4.
  1169. * @param w Fourth float in float4.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1173. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color3 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @returns this effect.
  1183. */
  1184. Effect.prototype.setColor3 = function (uniformName, color3) {
  1185. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1186. this._engine.setColor3(this.getUniform(uniformName), color3);
  1187. }
  1188. return this;
  1189. };
  1190. /**
  1191. * Sets a Color4 on a uniform variable.
  1192. * @param uniformName Name of the variable.
  1193. * @param color3 Value to be set.
  1194. * @param alpha Alpha value to be set.
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1198. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1199. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * Sets a Color4 on a uniform variable
  1205. * @param uniformName defines the name of the variable
  1206. * @param color4 defines the value to be set
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1210. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1211. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Resets the cache of effects.
  1217. */
  1218. Effect.ResetCache = function () {
  1219. Effect._baseCache = {};
  1220. };
  1221. Effect._uniqueIdSeed = 0;
  1222. Effect._baseCache = {};
  1223. /**
  1224. * Store of each shader (The can be looked up using effect.key)
  1225. */
  1226. Effect.ShadersStore = {};
  1227. /**
  1228. * Store of each included file for a shader (The can be looked up using effect.key)
  1229. */
  1230. Effect.IncludesShadersStore = {};
  1231. return Effect;
  1232. }());
  1233. BABYLON.Effect = Effect;
  1234. })(BABYLON || (BABYLON = {}));
  1235. //# sourceMappingURL=babylon.effect.js.map
  1236. //# sourceMappingURL=babylon.types.js.map
  1237. var BABYLON;
  1238. (function (BABYLON) {
  1239. var KeyboardEventTypes = /** @class */ (function () {
  1240. function KeyboardEventTypes() {
  1241. }
  1242. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1243. get: function () {
  1244. return KeyboardEventTypes._KEYDOWN;
  1245. },
  1246. enumerable: true,
  1247. configurable: true
  1248. });
  1249. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1250. get: function () {
  1251. return KeyboardEventTypes._KEYUP;
  1252. },
  1253. enumerable: true,
  1254. configurable: true
  1255. });
  1256. KeyboardEventTypes._KEYDOWN = 0x01;
  1257. KeyboardEventTypes._KEYUP = 0x02;
  1258. return KeyboardEventTypes;
  1259. }());
  1260. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. function KeyboardInfo(type, event) {
  1263. this.type = type;
  1264. this.event = event;
  1265. }
  1266. return KeyboardInfo;
  1267. }());
  1268. BABYLON.KeyboardInfo = KeyboardInfo;
  1269. /**
  1270. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1271. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1272. */
  1273. var KeyboardInfoPre = /** @class */ (function (_super) {
  1274. __extends(KeyboardInfoPre, _super);
  1275. function KeyboardInfoPre(type, event) {
  1276. var _this = _super.call(this, type, event) || this;
  1277. _this.skipOnPointerObservable = false;
  1278. return _this;
  1279. }
  1280. return KeyboardInfoPre;
  1281. }(KeyboardInfo));
  1282. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1283. })(BABYLON || (BABYLON = {}));
  1284. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1285. var BABYLON;
  1286. (function (BABYLON) {
  1287. var PointerEventTypes = /** @class */ (function () {
  1288. function PointerEventTypes() {
  1289. }
  1290. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1291. get: function () {
  1292. return PointerEventTypes._POINTERDOWN;
  1293. },
  1294. enumerable: true,
  1295. configurable: true
  1296. });
  1297. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1298. get: function () {
  1299. return PointerEventTypes._POINTERUP;
  1300. },
  1301. enumerable: true,
  1302. configurable: true
  1303. });
  1304. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1305. get: function () {
  1306. return PointerEventTypes._POINTERMOVE;
  1307. },
  1308. enumerable: true,
  1309. configurable: true
  1310. });
  1311. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1312. get: function () {
  1313. return PointerEventTypes._POINTERWHEEL;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1319. get: function () {
  1320. return PointerEventTypes._POINTERPICK;
  1321. },
  1322. enumerable: true,
  1323. configurable: true
  1324. });
  1325. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1326. get: function () {
  1327. return PointerEventTypes._POINTERTAP;
  1328. },
  1329. enumerable: true,
  1330. configurable: true
  1331. });
  1332. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1333. get: function () {
  1334. return PointerEventTypes._POINTERDOUBLETAP;
  1335. },
  1336. enumerable: true,
  1337. configurable: true
  1338. });
  1339. PointerEventTypes._POINTERDOWN = 0x01;
  1340. PointerEventTypes._POINTERUP = 0x02;
  1341. PointerEventTypes._POINTERMOVE = 0x04;
  1342. PointerEventTypes._POINTERWHEEL = 0x08;
  1343. PointerEventTypes._POINTERPICK = 0x10;
  1344. PointerEventTypes._POINTERTAP = 0x20;
  1345. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1346. return PointerEventTypes;
  1347. }());
  1348. BABYLON.PointerEventTypes = PointerEventTypes;
  1349. var PointerInfoBase = /** @class */ (function () {
  1350. function PointerInfoBase(type, event) {
  1351. this.type = type;
  1352. this.event = event;
  1353. }
  1354. return PointerInfoBase;
  1355. }());
  1356. BABYLON.PointerInfoBase = PointerInfoBase;
  1357. /**
  1358. * This class is used to store pointer related info for the onPrePointerObservable event.
  1359. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1360. */
  1361. var PointerInfoPre = /** @class */ (function (_super) {
  1362. __extends(PointerInfoPre, _super);
  1363. function PointerInfoPre(type, event, localX, localY) {
  1364. var _this = _super.call(this, type, event) || this;
  1365. _this.skipOnPointerObservable = false;
  1366. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1367. return _this;
  1368. }
  1369. return PointerInfoPre;
  1370. }(PointerInfoBase));
  1371. BABYLON.PointerInfoPre = PointerInfoPre;
  1372. /**
  1373. * This type contains all the data related to a pointer event in Babylon.js.
  1374. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1375. */
  1376. var PointerInfo = /** @class */ (function (_super) {
  1377. __extends(PointerInfo, _super);
  1378. function PointerInfo(type, event, pickInfo) {
  1379. var _this = _super.call(this, type, event) || this;
  1380. _this.pickInfo = pickInfo;
  1381. return _this;
  1382. }
  1383. return PointerInfo;
  1384. }(PointerInfoBase));
  1385. BABYLON.PointerInfo = PointerInfo;
  1386. })(BABYLON || (BABYLON = {}));
  1387. //# sourceMappingURL=babylon.pointerEvents.js.map
  1388. var BABYLON;
  1389. (function (BABYLON) {
  1390. BABYLON.ToGammaSpace = 1 / 2.2;
  1391. BABYLON.ToLinearSpace = 2.2;
  1392. BABYLON.Epsilon = 0.001;
  1393. /**
  1394. * Class used to hold a RBG color
  1395. */
  1396. var Color3 = /** @class */ (function () {
  1397. /**
  1398. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1399. * @param r defines the red component (between 0 and 1, default is 0)
  1400. * @param g defines the green component (between 0 and 1, default is 0)
  1401. * @param b defines the blue component (between 0 and 1, default is 0)
  1402. */
  1403. function Color3(
  1404. /**
  1405. * Defines the red component (between 0 and 1, default is 0)
  1406. */
  1407. r,
  1408. /**
  1409. * Defines the green component (between 0 and 1, default is 0)
  1410. */
  1411. g,
  1412. /**
  1413. * Defines the blue component (between 0 and 1, default is 0)
  1414. */
  1415. b) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. this.r = r;
  1420. this.g = g;
  1421. this.b = b;
  1422. }
  1423. /**
  1424. * Creates a string with the Color3 current values
  1425. * @returns the string representation of the Color3 object
  1426. */
  1427. Color3.prototype.toString = function () {
  1428. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1429. };
  1430. /**
  1431. * Returns the string "Color3"
  1432. * @returns "Color3"
  1433. */
  1434. Color3.prototype.getClassName = function () {
  1435. return "Color3";
  1436. };
  1437. /**
  1438. * Compute the Color3 hash code
  1439. * @returns an unique number that can be used to hash Color3 objects
  1440. */
  1441. Color3.prototype.getHashCode = function () {
  1442. var hash = this.r || 0;
  1443. hash = (hash * 397) ^ (this.g || 0);
  1444. hash = (hash * 397) ^ (this.b || 0);
  1445. return hash;
  1446. };
  1447. // Operators
  1448. /**
  1449. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1450. * @param array defines the array where to store the r,g,b components
  1451. * @param index defines an optional index in the target array to define where to start storing values
  1452. * @returns the current Color3 object
  1453. */
  1454. Color3.prototype.toArray = function (array, index) {
  1455. if (index === undefined) {
  1456. index = 0;
  1457. }
  1458. array[index] = this.r;
  1459. array[index + 1] = this.g;
  1460. array[index + 2] = this.b;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1465. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1466. * @returns a new {BABYLON.Color4} object
  1467. */
  1468. Color3.prototype.toColor4 = function (alpha) {
  1469. if (alpha === void 0) { alpha = 1; }
  1470. return new Color4(this.r, this.g, this.b, alpha);
  1471. };
  1472. /**
  1473. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1474. * @returns the new array
  1475. */
  1476. Color3.prototype.asArray = function () {
  1477. var result = new Array();
  1478. this.toArray(result, 0);
  1479. return result;
  1480. };
  1481. /**
  1482. * Returns the luminance value
  1483. * @returns a float value
  1484. */
  1485. Color3.prototype.toLuminance = function () {
  1486. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1487. };
  1488. /**
  1489. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1490. * @param otherColor defines the second operand
  1491. * @returns the new Color3 object
  1492. */
  1493. Color3.prototype.multiply = function (otherColor) {
  1494. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1495. };
  1496. /**
  1497. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1498. * @param otherColor defines the second operand
  1499. * @param result defines the Color3 object where to store the result
  1500. * @returns the current Color3
  1501. */
  1502. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1503. result.r = this.r * otherColor.r;
  1504. result.g = this.g * otherColor.g;
  1505. result.b = this.b * otherColor.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Determines equality between Color3 objects
  1510. * @param otherColor defines the second operand
  1511. * @returns true if the rgb values are equal to the given ones
  1512. */
  1513. Color3.prototype.equals = function (otherColor) {
  1514. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1515. };
  1516. /**
  1517. * Determines equality between the current Color3 object and a set of r,b,g values
  1518. * @param r defines the red component to check
  1519. * @param g defines the green component to check
  1520. * @param b defines the blue component to check
  1521. * @returns true if the rgb values are equal to the given ones
  1522. */
  1523. Color3.prototype.equalsFloats = function (r, g, b) {
  1524. return this.r === r && this.g === g && this.b === b;
  1525. };
  1526. /**
  1527. * Multiplies in place each rgb value by scale
  1528. * @param scale defines the scaling factor
  1529. * @returns the updated Color3
  1530. */
  1531. Color3.prototype.scale = function (scale) {
  1532. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1533. };
  1534. /**
  1535. * Multiplies the rgb values by scale and stores the result into "result"
  1536. * @param scale defines the scaling factor
  1537. * @param result defines the Color3 object where to store the result
  1538. * @returns the unmodified current Color3
  1539. */
  1540. Color3.prototype.scaleToRef = function (scale, result) {
  1541. result.r = this.r * scale;
  1542. result.g = this.g * scale;
  1543. result.b = this.b * scale;
  1544. return this;
  1545. };
  1546. /**
  1547. * Scale the current Color3 values by a factor and add the result to a given Color3
  1548. * @param scale defines the scale factor
  1549. * @param result defines color to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1553. result.r += this.r * scale;
  1554. result.g += this.g * scale;
  1555. result.b += this.b * scale;
  1556. return this;
  1557. };
  1558. /**
  1559. * Clamps the rgb values by the min and max values and stores the result into "result"
  1560. * @param min defines minimum clamping value (default is 0)
  1561. * @param max defines maximum clamping value (default is 1)
  1562. * @param result defines color to store the result into
  1563. * @returns the original Color3
  1564. */
  1565. Color3.prototype.clampToRef = function (min, max, result) {
  1566. if (min === void 0) { min = 0; }
  1567. if (max === void 0) { max = 1; }
  1568. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1569. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1570. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1571. return this;
  1572. };
  1573. /**
  1574. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.add = function (otherColor) {
  1579. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.addToRef = function (otherColor, result) {
  1588. result.r = this.r + otherColor.r;
  1589. result.g = this.g + otherColor.g;
  1590. result.b = this.b + otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3
  1597. */
  1598. Color3.prototype.subtract = function (otherColor) {
  1599. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1600. };
  1601. /**
  1602. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines Color3 object to store the result into
  1605. * @returns the unmodified current Color3
  1606. */
  1607. Color3.prototype.subtractToRef = function (otherColor, result) {
  1608. result.r = this.r - otherColor.r;
  1609. result.g = this.g - otherColor.g;
  1610. result.b = this.b - otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Copy the current object
  1615. * @returns a new Color3 copied the current one
  1616. */
  1617. Color3.prototype.clone = function () {
  1618. return new Color3(this.r, this.g, this.b);
  1619. };
  1620. /**
  1621. * Copies the rgb values from the source in the current Color3
  1622. * @param source defines the source Color3 object
  1623. * @returns the updated Color3 object
  1624. */
  1625. Color3.prototype.copyFrom = function (source) {
  1626. this.r = source.r;
  1627. this.g = source.g;
  1628. this.b = source.b;
  1629. return this;
  1630. };
  1631. /**
  1632. * Updates the Color3 rgb values from the given floats
  1633. * @param r defines the red component to read from
  1634. * @param g defines the green component to read from
  1635. * @param b defines the blue component to read from
  1636. * @returns the current Color3 object
  1637. */
  1638. Color3.prototype.copyFromFloats = function (r, g, b) {
  1639. this.r = r;
  1640. this.g = g;
  1641. this.b = b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Updates the Color3 rgb values from the given floats
  1646. * @param r defines the red component to read from
  1647. * @param g defines the green component to read from
  1648. * @param b defines the blue component to read from
  1649. * @returns the current Color3 object
  1650. */
  1651. Color3.prototype.set = function (r, g, b) {
  1652. return this.copyFromFloats(r, g, b);
  1653. };
  1654. /**
  1655. * Compute the Color3 hexadecimal code as a string
  1656. * @returns a string containing the hexadecimal representation of the Color3 object
  1657. */
  1658. Color3.prototype.toHexString = function () {
  1659. var intR = (this.r * 255) | 0;
  1660. var intG = (this.g * 255) | 0;
  1661. var intB = (this.b * 255) | 0;
  1662. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to linear space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toLinearSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toLinearSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the linear space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1682. return this;
  1683. };
  1684. /**
  1685. * Computes a new Color3 converted from the current one to gamma space
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.prototype.toGammaSpace = function () {
  1689. var convertedColor = new Color3();
  1690. this.toGammaSpaceToRef(convertedColor);
  1691. return convertedColor;
  1692. };
  1693. /**
  1694. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1695. * @param convertedColor defines the Color3 object where to store the gamma space version
  1696. * @returns the unmodified Color3
  1697. */
  1698. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1699. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1700. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1701. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1702. return this;
  1703. };
  1704. // Statics
  1705. /**
  1706. * Creates a new Color3 from the string containing valid hexadecimal values
  1707. * @param hex defines a string containing valid hexadecimal values
  1708. * @returns a new Color3 object
  1709. */
  1710. Color3.FromHexString = function (hex) {
  1711. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1712. return new Color3(0, 0, 0);
  1713. }
  1714. var r = parseInt(hex.substring(1, 3), 16);
  1715. var g = parseInt(hex.substring(3, 5), 16);
  1716. var b = parseInt(hex.substring(5, 7), 16);
  1717. return Color3.FromInts(r, g, b);
  1718. };
  1719. /**
  1720. * Creates a new Vector3 from the starting index of the given array
  1721. * @param array defines the source array
  1722. * @param offset defines an offset in the source array
  1723. * @returns a new Color3 object
  1724. */
  1725. Color3.FromArray = function (array, offset) {
  1726. if (offset === void 0) { offset = 0; }
  1727. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1728. };
  1729. /**
  1730. * Creates a new Color3 from integer values (< 256)
  1731. * @param r defines the red component to read from (value between 0 and 255)
  1732. * @param g defines the green component to read from (value between 0 and 255)
  1733. * @param b defines the blue component to read from (value between 0 and 255)
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.FromInts = function (r, g, b) {
  1737. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1738. };
  1739. /**
  1740. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1741. * @param start defines the start Color3 value
  1742. * @param end defines the end Color3 value
  1743. * @param amount defines the gradient value between start and end
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Lerp = function (start, end, amount) {
  1747. var r = start.r + ((end.r - start.r) * amount);
  1748. var g = start.g + ((end.g - start.g) * amount);
  1749. var b = start.b + ((end.b - start.b) * amount);
  1750. return new Color3(r, g, b);
  1751. };
  1752. /**
  1753. * Returns a Color3 value containing a red color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Red = function () { return new Color3(1, 0, 0); };
  1757. /**
  1758. * Returns a Color3 value containing a green color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Green = function () { return new Color3(0, 1, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a blue color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a black color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Black = function () { return new Color3(0, 0, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a white color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.White = function () { return new Color3(1, 1, 1); };
  1777. /**
  1778. * Returns a Color3 value containing a purple color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1782. /**
  1783. * Returns a Color3 value containing a magenta color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1787. /**
  1788. * Returns a Color3 value containing a yellow color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1792. /**
  1793. * Returns a Color3 value containing a gray color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1797. /**
  1798. * Returns a Color3 value containing a teal color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1802. /**
  1803. * Returns a Color3 value containing a random color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1807. return Color3;
  1808. }());
  1809. BABYLON.Color3 = Color3;
  1810. /**
  1811. * Class used to hold a RBGA color
  1812. */
  1813. var Color4 = /** @class */ (function () {
  1814. /**
  1815. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1816. * @param r defines the red component (between 0 and 1, default is 0)
  1817. * @param g defines the green component (between 0 and 1, default is 0)
  1818. * @param b defines the blue component (between 0 and 1, default is 0)
  1819. * @param a defines the alpha component (between 0 and 1, default is 1)
  1820. */
  1821. function Color4(
  1822. /**
  1823. * Defines the red component (between 0 and 1, default is 0)
  1824. */
  1825. r,
  1826. /**
  1827. * Defines the green component (between 0 and 1, default is 0)
  1828. */
  1829. g,
  1830. /**
  1831. * Defines the blue component (between 0 and 1, default is 0)
  1832. */
  1833. b,
  1834. /**
  1835. * Defines the alpha component (between 0 and 1, default is 1)
  1836. */
  1837. a) {
  1838. if (r === void 0) { r = 0; }
  1839. if (g === void 0) { g = 0; }
  1840. if (b === void 0) { b = 0; }
  1841. if (a === void 0) { a = 1; }
  1842. this.r = r;
  1843. this.g = g;
  1844. this.b = b;
  1845. this.a = a;
  1846. }
  1847. // Operators
  1848. /**
  1849. * Adds in place the given Color4 values to the current Color4 object
  1850. * @param right defines the second operand
  1851. * @returns the current updated Color4 object
  1852. */
  1853. Color4.prototype.addInPlace = function (right) {
  1854. this.r += right.r;
  1855. this.g += right.g;
  1856. this.b += right.b;
  1857. this.a += right.a;
  1858. return this;
  1859. };
  1860. /**
  1861. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1862. * @returns the new array
  1863. */
  1864. Color4.prototype.asArray = function () {
  1865. var result = new Array();
  1866. this.toArray(result, 0);
  1867. return result;
  1868. };
  1869. /**
  1870. * Stores from the starting index in the given array the Color4 successive values
  1871. * @param array defines the array where to store the r,g,b components
  1872. * @param index defines an optional index in the target array to define where to start storing values
  1873. * @returns the current Color4 object
  1874. */
  1875. Color4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.r;
  1880. array[index + 1] = this.g;
  1881. array[index + 2] = this.b;
  1882. array[index + 3] = this.a;
  1883. return this;
  1884. };
  1885. /**
  1886. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1887. * @param right defines the second operand
  1888. * @returns a new Color4 object
  1889. */
  1890. Color4.prototype.add = function (right) {
  1891. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1892. };
  1893. /**
  1894. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1895. * @param right defines the second operand
  1896. * @returns a new Color4 object
  1897. */
  1898. Color4.prototype.subtract = function (right) {
  1899. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1900. };
  1901. /**
  1902. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1903. * @param right defines the second operand
  1904. * @param result defines the Color4 object where to store the result
  1905. * @returns the current Color4 object
  1906. */
  1907. Color4.prototype.subtractToRef = function (right, result) {
  1908. result.r = this.r - right.r;
  1909. result.g = this.g - right.g;
  1910. result.b = this.b - right.b;
  1911. result.a = this.a - right.a;
  1912. return this;
  1913. };
  1914. /**
  1915. * Creates a new Color4 with the current Color4 values multiplied by scale
  1916. * @param scale defines the scaling factor to apply
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.scale = function (scale) {
  1920. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1921. };
  1922. /**
  1923. * Multiplies the current Color4 values by scale and stores the result in "result"
  1924. * @param scale defines the scaling factor to apply
  1925. * @param result defines the Color4 object where to store the result
  1926. * @returns the current unmodified Color4
  1927. */
  1928. Color4.prototype.scaleToRef = function (scale, result) {
  1929. result.r = this.r * scale;
  1930. result.g = this.g * scale;
  1931. result.b = this.b * scale;
  1932. result.a = this.a * scale;
  1933. return this;
  1934. };
  1935. /**
  1936. * Scale the current Color4 values by a factor and add the result to a given Color4
  1937. * @param scale defines the scale factor
  1938. * @param result defines the Color4 object where to store the result
  1939. * @returns the unmodified current Color4
  1940. */
  1941. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1942. result.r += this.r * scale;
  1943. result.g += this.g * scale;
  1944. result.b += this.b * scale;
  1945. result.a += this.a * scale;
  1946. return this;
  1947. };
  1948. /**
  1949. * Clamps the rgb values by the min and max values and stores the result into "result"
  1950. * @param min defines minimum clamping value (default is 0)
  1951. * @param max defines maximum clamping value (default is 1)
  1952. * @param result defines color to store the result into.
  1953. * @returns the cuurent Color4
  1954. */
  1955. Color4.prototype.clampToRef = function (min, max, result) {
  1956. if (min === void 0) { min = 0; }
  1957. if (max === void 0) { max = 1; }
  1958. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1959. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1960. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1961. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1962. return this;
  1963. };
  1964. /**
  1965. * Multipy an Color4 value by another and return a new Color4 object
  1966. * @param color defines the Color4 value to multiply by
  1967. * @returns a new Color4 object
  1968. */
  1969. Color4.prototype.multiply = function (color) {
  1970. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1971. };
  1972. /**
  1973. * Multipy a Color4 value by another and push the result in a reference value
  1974. * @param color defines the Color4 value to multiply by
  1975. * @param result defines the Color4 to fill the result in
  1976. * @returns the result Color4
  1977. */
  1978. Color4.prototype.multiplyToRef = function (color, result) {
  1979. result.r = this.r * color.r;
  1980. result.g = this.g * color.g;
  1981. result.b = this.b * color.b;
  1982. result.a = this.a * color.a;
  1983. return result;
  1984. };
  1985. /**
  1986. * Creates a string with the Color4 current values
  1987. * @returns the string representation of the Color4 object
  1988. */
  1989. Color4.prototype.toString = function () {
  1990. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1991. };
  1992. /**
  1993. * Returns the string "Color4"
  1994. * @returns "Color4"
  1995. */
  1996. Color4.prototype.getClassName = function () {
  1997. return "Color4";
  1998. };
  1999. /**
  2000. * Compute the Color4 hash code
  2001. * @returns an unique number that can be used to hash Color4 objects
  2002. */
  2003. Color4.prototype.getHashCode = function () {
  2004. var hash = this.r || 0;
  2005. hash = (hash * 397) ^ (this.g || 0);
  2006. hash = (hash * 397) ^ (this.b || 0);
  2007. hash = (hash * 397) ^ (this.a || 0);
  2008. return hash;
  2009. };
  2010. /**
  2011. * Creates a new Color4 copied from the current one
  2012. * @returns a new Color4 object
  2013. */
  2014. Color4.prototype.clone = function () {
  2015. return new Color4(this.r, this.g, this.b, this.a);
  2016. };
  2017. /**
  2018. * Copies the given Color4 values into the current one
  2019. * @param source defines the source Color4 object
  2020. * @returns the current updated Color4 object
  2021. */
  2022. Color4.prototype.copyFrom = function (source) {
  2023. this.r = source.r;
  2024. this.g = source.g;
  2025. this.b = source.b;
  2026. this.a = source.a;
  2027. return this;
  2028. };
  2029. /**
  2030. * Copies the given float values into the current one
  2031. * @param r defines the red component to read from
  2032. * @param g defines the green component to read from
  2033. * @param b defines the blue component to read from
  2034. * @param a defines the alpha component to read from
  2035. * @returns the current updated Color4 object
  2036. */
  2037. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2038. this.r = r;
  2039. this.g = g;
  2040. this.b = b;
  2041. this.a = a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Copies the given float values into the current one
  2046. * @param r defines the red component to read from
  2047. * @param g defines the green component to read from
  2048. * @param b defines the blue component to read from
  2049. * @param a defines the alpha component to read from
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.set = function (r, g, b, a) {
  2053. return this.copyFromFloats(r, g, b, a);
  2054. };
  2055. /**
  2056. * Compute the Color4 hexadecimal code as a string
  2057. * @returns a string containing the hexadecimal representation of the Color4 object
  2058. */
  2059. Color4.prototype.toHexString = function () {
  2060. var intR = (this.r * 255) | 0;
  2061. var intG = (this.g * 255) | 0;
  2062. var intB = (this.b * 255) | 0;
  2063. var intA = (this.a * 255) | 0;
  2064. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2065. };
  2066. /**
  2067. * Computes a new Color4 converted from the current one to linear space
  2068. * @returns a new Color4 object
  2069. */
  2070. Color4.prototype.toLinearSpace = function () {
  2071. var convertedColor = new Color4();
  2072. this.toLinearSpaceToRef(convertedColor);
  2073. return convertedColor;
  2074. };
  2075. /**
  2076. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2077. * @param convertedColor defines the Color4 object where to store the linear space version
  2078. * @returns the unmodified Color4
  2079. */
  2080. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2081. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2082. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2083. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2084. convertedColor.a = this.a;
  2085. return this;
  2086. };
  2087. /**
  2088. * Computes a new Color4 converted from the current one to gamma space
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.prototype.toGammaSpace = function () {
  2092. var convertedColor = new Color4();
  2093. this.toGammaSpaceToRef(convertedColor);
  2094. return convertedColor;
  2095. };
  2096. /**
  2097. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2098. * @param convertedColor defines the Color4 object where to store the gamma space version
  2099. * @returns the unmodified Color4
  2100. */
  2101. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2102. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2103. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2104. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2105. convertedColor.a = this.a;
  2106. return this;
  2107. };
  2108. // Statics
  2109. /**
  2110. * Creates a new Color4 from the string containing valid hexadecimal values
  2111. * @param hex defines a string containing valid hexadecimal values
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.FromHexString = function (hex) {
  2115. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2116. return new Color4(0.0, 0.0, 0.0, 0.0);
  2117. }
  2118. var r = parseInt(hex.substring(1, 3), 16);
  2119. var g = parseInt(hex.substring(3, 5), 16);
  2120. var b = parseInt(hex.substring(5, 7), 16);
  2121. var a = parseInt(hex.substring(7, 9), 16);
  2122. return Color4.FromInts(r, g, b, a);
  2123. };
  2124. /**
  2125. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2126. * @param left defines the start value
  2127. * @param right defines the end value
  2128. * @param amount defines the gradient factor
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.Lerp = function (left, right, amount) {
  2132. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2133. Color4.LerpToRef(left, right, amount, result);
  2134. return result;
  2135. };
  2136. /**
  2137. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2138. * @param left defines the start value
  2139. * @param right defines the end value
  2140. * @param amount defines the gradient factor
  2141. * @param result defines the Color4 object where to store data
  2142. */
  2143. Color4.LerpToRef = function (left, right, amount, result) {
  2144. result.r = left.r + (right.r - left.r) * amount;
  2145. result.g = left.g + (right.g - left.g) * amount;
  2146. result.b = left.b + (right.b - left.b) * amount;
  2147. result.a = left.a + (right.a - left.a) * amount;
  2148. };
  2149. /**
  2150. * Creates a new Color4 from the starting index element of the given array
  2151. * @param array defines the source array to read from
  2152. * @param offset defines the offset in the source array
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.FromArray = function (array, offset) {
  2156. if (offset === void 0) { offset = 0; }
  2157. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2158. };
  2159. /**
  2160. * Creates a new Color3 from integer values (< 256)
  2161. * @param r defines the red component to read from (value between 0 and 255)
  2162. * @param g defines the green component to read from (value between 0 and 255)
  2163. * @param b defines the blue component to read from (value between 0 and 255)
  2164. * @param a defines the alpha component to read from (value between 0 and 255)
  2165. * @returns a new Color3 object
  2166. */
  2167. Color4.FromInts = function (r, g, b, a) {
  2168. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2169. };
  2170. /**
  2171. * Check the content of a given array and convert it to an array containing RGBA data
  2172. * If the original array was already containing count * 4 values then it is returned directly
  2173. * @param colors defines the array to check
  2174. * @param count defines the number of RGBA data to expect
  2175. * @returns an array containing count * 4 values (RGBA)
  2176. */
  2177. Color4.CheckColors4 = function (colors, count) {
  2178. // Check if color3 was used
  2179. if (colors.length === count * 3) {
  2180. var colors4 = [];
  2181. for (var index = 0; index < colors.length; index += 3) {
  2182. var newIndex = (index / 3) * 4;
  2183. colors4[newIndex] = colors[index];
  2184. colors4[newIndex + 1] = colors[index + 1];
  2185. colors4[newIndex + 2] = colors[index + 2];
  2186. colors4[newIndex + 3] = 1.0;
  2187. }
  2188. return colors4;
  2189. }
  2190. return colors;
  2191. };
  2192. return Color4;
  2193. }());
  2194. BABYLON.Color4 = Color4;
  2195. /**
  2196. * Class representing a vector containing 2 coordinates
  2197. */
  2198. var Vector2 = /** @class */ (function () {
  2199. /**
  2200. * Creates a new Vector2 from the given x and y coordinates
  2201. * @param x defines the first coordinate
  2202. * @param y defines the second coordinate
  2203. */
  2204. function Vector2(
  2205. /** defines the first coordinate */
  2206. x,
  2207. /** defines the second coordinate */
  2208. y) {
  2209. this.x = x;
  2210. this.y = y;
  2211. }
  2212. /**
  2213. * Gets a string with the Vector2 coordinates
  2214. * @returns a string with the Vector2 coordinates
  2215. */
  2216. Vector2.prototype.toString = function () {
  2217. return "{X: " + this.x + " Y:" + this.y + "}";
  2218. };
  2219. /**
  2220. * Gets class name
  2221. * @returns the string "Vector2"
  2222. */
  2223. Vector2.prototype.getClassName = function () {
  2224. return "Vector2";
  2225. };
  2226. /**
  2227. * Gets current vector hash code
  2228. * @returns the Vector2 hash code as a number
  2229. */
  2230. Vector2.prototype.getHashCode = function () {
  2231. var hash = this.x || 0;
  2232. hash = (hash * 397) ^ (this.y || 0);
  2233. return hash;
  2234. };
  2235. // Operators
  2236. /**
  2237. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2238. * @param array defines the source array
  2239. * @param index defines the offset in source array
  2240. * @returns the current Vector2
  2241. */
  2242. Vector2.prototype.toArray = function (array, index) {
  2243. if (index === void 0) { index = 0; }
  2244. array[index] = this.x;
  2245. array[index + 1] = this.y;
  2246. return this;
  2247. };
  2248. /**
  2249. * Copy the current vector to an array
  2250. * @returns a new array with 2 elements: the Vector2 coordinates.
  2251. */
  2252. Vector2.prototype.asArray = function () {
  2253. var result = new Array();
  2254. this.toArray(result, 0);
  2255. return result;
  2256. };
  2257. /**
  2258. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2259. * @param source defines the source Vector2
  2260. * @returns the current updated Vector2
  2261. */
  2262. Vector2.prototype.copyFrom = function (source) {
  2263. this.x = source.x;
  2264. this.y = source.y;
  2265. return this;
  2266. };
  2267. /**
  2268. * Sets the Vector2 coordinates with the given floats
  2269. * @param x defines the first coordinate
  2270. * @param y defines the second coordinate
  2271. * @returns the current updated Vector2
  2272. */
  2273. Vector2.prototype.copyFromFloats = function (x, y) {
  2274. this.x = x;
  2275. this.y = y;
  2276. return this;
  2277. };
  2278. /**
  2279. * Sets the Vector2 coordinates with the given floats
  2280. * @param x defines the first coordinate
  2281. * @param y defines the second coordinate
  2282. * @returns the current updated Vector2
  2283. */
  2284. Vector2.prototype.set = function (x, y) {
  2285. return this.copyFromFloats(x, y);
  2286. };
  2287. /**
  2288. * Add another vector with the current one
  2289. * @param otherVector defines the other vector
  2290. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2291. */
  2292. Vector2.prototype.add = function (otherVector) {
  2293. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2294. };
  2295. /**
  2296. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2297. * @param otherVector defines the other vector
  2298. * @param result defines the target vector
  2299. * @returns the unmodified current Vector2
  2300. */
  2301. Vector2.prototype.addToRef = function (otherVector, result) {
  2302. result.x = this.x + otherVector.x;
  2303. result.y = this.y + otherVector.y;
  2304. return this;
  2305. };
  2306. /**
  2307. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2308. * @param otherVector defines the other vector
  2309. * @returns the current updated Vector2
  2310. */
  2311. Vector2.prototype.addInPlace = function (otherVector) {
  2312. this.x += otherVector.x;
  2313. this.y += otherVector.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2318. * @param otherVector defines the other vector
  2319. * @returns a new Vector2
  2320. */
  2321. Vector2.prototype.addVector3 = function (otherVector) {
  2322. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2323. };
  2324. /**
  2325. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2326. * @param otherVector defines the other vector
  2327. * @returns a new Vector2
  2328. */
  2329. Vector2.prototype.subtract = function (otherVector) {
  2330. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2331. };
  2332. /**
  2333. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2334. * @param otherVector defines the other vector
  2335. * @param result defines the target vector
  2336. * @returns the unmodified current Vector2
  2337. */
  2338. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2339. result.x = this.x - otherVector.x;
  2340. result.y = this.y - otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2345. * @param otherVector defines the other vector
  2346. * @returns the current updated Vector2
  2347. */
  2348. Vector2.prototype.subtractInPlace = function (otherVector) {
  2349. this.x -= otherVector.x;
  2350. this.y -= otherVector.y;
  2351. return this;
  2352. };
  2353. /**
  2354. * Multiplies in place the current Vector2 coordinates by the given ones
  2355. * @param otherVector defines the other vector
  2356. * @returns the current updated Vector2
  2357. */
  2358. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2359. this.x *= otherVector.x;
  2360. this.y *= otherVector.y;
  2361. return this;
  2362. };
  2363. /**
  2364. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2365. * @param otherVector defines the other vector
  2366. * @returns a new Vector2
  2367. */
  2368. Vector2.prototype.multiply = function (otherVector) {
  2369. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2370. };
  2371. /**
  2372. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @param result defines the target vector
  2375. * @returns the unmodified current Vector2
  2376. */
  2377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2378. result.x = this.x * otherVector.x;
  2379. result.y = this.y * otherVector.y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2384. * @param x defines the first coordinate
  2385. * @param y defines the second coordinate
  2386. * @returns a new Vector2
  2387. */
  2388. Vector2.prototype.multiplyByFloats = function (x, y) {
  2389. return new Vector2(this.x * x, this.y * y);
  2390. };
  2391. /**
  2392. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2393. * @param otherVector defines the other vector
  2394. * @returns a new Vector2
  2395. */
  2396. Vector2.prototype.divide = function (otherVector) {
  2397. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2398. };
  2399. /**
  2400. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @param result defines the target vector
  2403. * @returns the unmodified current Vector2
  2404. */
  2405. Vector2.prototype.divideToRef = function (otherVector, result) {
  2406. result.x = this.x / otherVector.x;
  2407. result.y = this.y / otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Divides the current Vector3 coordinates by the given ones
  2412. * @param otherVector defines the other vector
  2413. * @returns the current updated Vector2
  2414. */
  2415. Vector2.prototype.divideInPlace = function (otherVector) {
  2416. return this.divideToRef(otherVector, this);
  2417. };
  2418. /**
  2419. * Gets a new Vector2 with current Vector2 negated coordinates
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.negate = function () {
  2423. return new Vector2(-this.x, -this.y);
  2424. };
  2425. /**
  2426. * Multiply the Vector2 coordinates by scale
  2427. * @param scale defines the scaling factor
  2428. * @returns the current updated Vector2
  2429. */
  2430. Vector2.prototype.scaleInPlace = function (scale) {
  2431. this.x *= scale;
  2432. this.y *= scale;
  2433. return this;
  2434. };
  2435. /**
  2436. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2437. * @param scale defines the scaling factor
  2438. * @returns a new Vector2
  2439. */
  2440. Vector2.prototype.scale = function (scale) {
  2441. var result = new Vector2(0, 0);
  2442. this.scaleToRef(scale, result);
  2443. return result;
  2444. };
  2445. /**
  2446. * Scale the current Vector2 values by a factor to a given Vector2
  2447. * @param scale defines the scale factor
  2448. * @param result defines the Vector2 object where to store the result
  2449. * @returns the unmodified current Vector2
  2450. */
  2451. Vector2.prototype.scaleToRef = function (scale, result) {
  2452. result.x = this.x * scale;
  2453. result.y = this.y * scale;
  2454. return this;
  2455. };
  2456. /**
  2457. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2458. * @param scale defines the scale factor
  2459. * @param result defines the Vector2 object where to store the result
  2460. * @returns the unmodified current Vector2
  2461. */
  2462. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2463. result.x += this.x * scale;
  2464. result.y += this.y * scale;
  2465. return this;
  2466. };
  2467. /**
  2468. * Gets a boolean if two vectors are equals
  2469. * @param otherVector defines the other vector
  2470. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2471. */
  2472. Vector2.prototype.equals = function (otherVector) {
  2473. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2474. };
  2475. /**
  2476. * Gets a boolean if two vectors are equals (using an epsilon value)
  2477. * @param otherVector defines the other vector
  2478. * @param epsilon defines the minimal distance to consider equality
  2479. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2480. */
  2481. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2482. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2483. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2484. };
  2485. // Properties
  2486. /**
  2487. * Gets the length of the vector
  2488. * @returns the vector length (float)
  2489. */
  2490. Vector2.prototype.length = function () {
  2491. return Math.sqrt(this.x * this.x + this.y * this.y);
  2492. };
  2493. /**
  2494. * Gets the vector squared length
  2495. * @returns the vector squared length (float)
  2496. */
  2497. Vector2.prototype.lengthSquared = function () {
  2498. return (this.x * this.x + this.y * this.y);
  2499. };
  2500. // Methods
  2501. /**
  2502. * Normalize the vector
  2503. * @returns the current updated Vector2
  2504. */
  2505. Vector2.prototype.normalize = function () {
  2506. var len = this.length();
  2507. if (len === 0)
  2508. return this;
  2509. var num = 1.0 / len;
  2510. this.x *= num;
  2511. this.y *= num;
  2512. return this;
  2513. };
  2514. /**
  2515. * Gets a new Vector2 copied from the Vector2
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.prototype.clone = function () {
  2519. return new Vector2(this.x, this.y);
  2520. };
  2521. // Statics
  2522. /**
  2523. * Gets a new Vector2(0, 0)
  2524. * @returns a new Vector2
  2525. */
  2526. Vector2.Zero = function () {
  2527. return new Vector2(0, 0);
  2528. };
  2529. /**
  2530. * Gets a new Vector2(1, 1)
  2531. * @returns a new Vector2
  2532. */
  2533. Vector2.One = function () {
  2534. return new Vector2(1, 1);
  2535. };
  2536. /**
  2537. * Gets a new Vector2 set from the given index element of the given array
  2538. * @param array defines the data source
  2539. * @param offset defines the offset in the data source
  2540. * @returns a new Vector2
  2541. */
  2542. Vector2.FromArray = function (array, offset) {
  2543. if (offset === void 0) { offset = 0; }
  2544. return new Vector2(array[offset], array[offset + 1]);
  2545. };
  2546. /**
  2547. * Sets "result" from the given index element of the given array
  2548. * @param array defines the data source
  2549. * @param offset defines the offset in the data source
  2550. * @param result defines the target vector
  2551. */
  2552. Vector2.FromArrayToRef = function (array, offset, result) {
  2553. result.x = array[offset];
  2554. result.y = array[offset + 1];
  2555. };
  2556. /**
  2557. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2558. * @param value1 defines 1st point of control
  2559. * @param value2 defines 2nd point of control
  2560. * @param value3 defines 3rd point of control
  2561. * @param value4 defines 4th point of control
  2562. * @param amount defines the interpolation factor
  2563. * @returns a new Vector2
  2564. */
  2565. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2566. var squared = amount * amount;
  2567. var cubed = amount * squared;
  2568. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2569. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2570. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2571. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2572. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2573. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2578. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2579. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2580. * @param value defines the value to clamp
  2581. * @param min defines the lower limit
  2582. * @param max defines the upper limit
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Clamp = function (value, min, max) {
  2586. var x = value.x;
  2587. x = (x > max.x) ? max.x : x;
  2588. x = (x < min.x) ? min.x : x;
  2589. var y = value.y;
  2590. y = (y > max.y) ? max.y : y;
  2591. y = (y < min.y) ? min.y : y;
  2592. return new Vector2(x, y);
  2593. };
  2594. /**
  2595. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2596. * @param value1 defines the 1st control point
  2597. * @param tangent1 defines the outgoing tangent
  2598. * @param value2 defines the 2nd control point
  2599. * @param tangent2 defines the incoming tangent
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2604. var squared = amount * amount;
  2605. var cubed = amount * squared;
  2606. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2607. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2608. var part3 = (cubed - (2.0 * squared)) + amount;
  2609. var part4 = cubed - squared;
  2610. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2611. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2612. return new Vector2(x, y);
  2613. };
  2614. /**
  2615. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2616. * @param start defines the start vector
  2617. * @param end defines the end vector
  2618. * @param amount defines the interpolation factor
  2619. * @returns a new Vector2
  2620. */
  2621. Vector2.Lerp = function (start, end, amount) {
  2622. var x = start.x + ((end.x - start.x) * amount);
  2623. var y = start.y + ((end.y - start.y) * amount);
  2624. return new Vector2(x, y);
  2625. };
  2626. /**
  2627. * Gets the dot product of the vector "left" and the vector "right"
  2628. * @param left defines first vector
  2629. * @param right defines second vector
  2630. * @returns the dot product (float)
  2631. */
  2632. Vector2.Dot = function (left, right) {
  2633. return left.x * right.x + left.y * right.y;
  2634. };
  2635. /**
  2636. * Returns a new Vector2 equal to the normalized given vector
  2637. * @param vector defines the vector to normalize
  2638. * @returns a new Vector2
  2639. */
  2640. Vector2.Normalize = function (vector) {
  2641. var newVector = vector.clone();
  2642. newVector.normalize();
  2643. return newVector;
  2644. };
  2645. /**
  2646. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2647. * @param left defines 1st vector
  2648. * @param right defines 2nd vector
  2649. * @returns a new Vector2
  2650. */
  2651. Vector2.Minimize = function (left, right) {
  2652. var x = (left.x < right.x) ? left.x : right.x;
  2653. var y = (left.y < right.y) ? left.y : right.y;
  2654. return new Vector2(x, y);
  2655. };
  2656. /**
  2657. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2658. * @param left defines 1st vector
  2659. * @param right defines 2nd vector
  2660. * @returns a new Vector2
  2661. */
  2662. Vector2.Maximize = function (left, right) {
  2663. var x = (left.x > right.x) ? left.x : right.x;
  2664. var y = (left.y > right.y) ? left.y : right.y;
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2669. * @param vector defines the vector to transform
  2670. * @param transformation defines the matrix to apply
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Transform = function (vector, transformation) {
  2674. var r = Vector2.Zero();
  2675. Vector2.TransformToRef(vector, transformation, r);
  2676. return r;
  2677. };
  2678. /**
  2679. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2680. * @param vector defines the vector to transform
  2681. * @param transformation defines the matrix to apply
  2682. * @param result defines the target vector
  2683. */
  2684. Vector2.TransformToRef = function (vector, transformation, result) {
  2685. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2686. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2687. result.x = x;
  2688. result.y = y;
  2689. };
  2690. /**
  2691. * Determines if a given vector is included in a triangle
  2692. * @param p defines the vector to test
  2693. * @param p0 defines 1st triangle point
  2694. * @param p1 defines 2nd triangle point
  2695. * @param p2 defines 3rd triangle point
  2696. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2697. */
  2698. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2699. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2700. var sign = a < 0 ? -1 : 1;
  2701. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2702. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2703. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2704. };
  2705. /**
  2706. * Gets the distance between the vectors "value1" and "value2"
  2707. * @param value1 defines first vector
  2708. * @param value2 defines second vector
  2709. * @returns the distance between vectors
  2710. */
  2711. Vector2.Distance = function (value1, value2) {
  2712. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2713. };
  2714. /**
  2715. * Returns the squared distance between the vectors "value1" and "value2"
  2716. * @param value1 defines first vector
  2717. * @param value2 defines second vector
  2718. * @returns the squared distance between vectors
  2719. */
  2720. Vector2.DistanceSquared = function (value1, value2) {
  2721. var x = value1.x - value2.x;
  2722. var y = value1.y - value2.y;
  2723. return (x * x) + (y * y);
  2724. };
  2725. /**
  2726. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2727. * @param value1 defines first vector
  2728. * @param value2 defines second vector
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Center = function (value1, value2) {
  2732. var center = value1.add(value2);
  2733. center.scaleInPlace(0.5);
  2734. return center;
  2735. };
  2736. /**
  2737. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2738. * @param p defines the middle point
  2739. * @param segA defines one point of the segment
  2740. * @param segB defines the other point of the segment
  2741. * @returns the shortest distance
  2742. */
  2743. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2744. var l2 = Vector2.DistanceSquared(segA, segB);
  2745. if (l2 === 0.0) {
  2746. return Vector2.Distance(p, segA);
  2747. }
  2748. var v = segB.subtract(segA);
  2749. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2750. var proj = segA.add(v.multiplyByFloats(t, t));
  2751. return Vector2.Distance(p, proj);
  2752. };
  2753. return Vector2;
  2754. }());
  2755. BABYLON.Vector2 = Vector2;
  2756. /**
  2757. * Classed used to store (x,y,z) vector representation
  2758. * A Vector3 is the main object used in 3D geometry
  2759. * It can represent etiher the coordinates of a point the space, either a direction
  2760. * Reminder: Babylon.js uses a left handed forward facing system
  2761. */
  2762. var Vector3 = /** @class */ (function () {
  2763. /**
  2764. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2765. * @param x defines the first coordinates (on X axis)
  2766. * @param y defines the second coordinates (on Y axis)
  2767. * @param z defines the third coordinates (on Z axis)
  2768. */
  2769. function Vector3(
  2770. /**
  2771. * Defines the first coordinates (on X axis)
  2772. */
  2773. x,
  2774. /**
  2775. * Defines the second coordinates (on Y axis)
  2776. */
  2777. y,
  2778. /**
  2779. * Defines the third coordinates (on Z axis)
  2780. */
  2781. z) {
  2782. this.x = x;
  2783. this.y = y;
  2784. this.z = z;
  2785. }
  2786. /**
  2787. * Creates a string representation of the Vector3
  2788. * @returns a string with the Vector3 coordinates.
  2789. */
  2790. Vector3.prototype.toString = function () {
  2791. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2792. };
  2793. /**
  2794. * Gets the class name
  2795. * @returns the string "Vector3"
  2796. */
  2797. Vector3.prototype.getClassName = function () {
  2798. return "Vector3";
  2799. };
  2800. /**
  2801. * Creates the Vector3 hash code
  2802. * @returns a number which tends to be unique between Vector3 instances
  2803. */
  2804. Vector3.prototype.getHashCode = function () {
  2805. var hash = this.x || 0;
  2806. hash = (hash * 397) ^ (this.y || 0);
  2807. hash = (hash * 397) ^ (this.z || 0);
  2808. return hash;
  2809. };
  2810. // Operators
  2811. /**
  2812. * Creates an array containing three elements : the coordinates of the Vector3
  2813. * @returns a new array of numbers
  2814. */
  2815. Vector3.prototype.asArray = function () {
  2816. var result = [];
  2817. this.toArray(result, 0);
  2818. return result;
  2819. };
  2820. /**
  2821. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2822. * @param array defines the destination array
  2823. * @param index defines the offset in the destination array
  2824. * @returns the current Vector3
  2825. */
  2826. Vector3.prototype.toArray = function (array, index) {
  2827. if (index === void 0) { index = 0; }
  2828. array[index] = this.x;
  2829. array[index + 1] = this.y;
  2830. array[index + 2] = this.z;
  2831. return this;
  2832. };
  2833. /**
  2834. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2835. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2836. */
  2837. Vector3.prototype.toQuaternion = function () {
  2838. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2839. };
  2840. /**
  2841. * Adds the given vector to the current Vector3
  2842. * @param otherVector defines the second operand
  2843. * @returns the current updated Vector3
  2844. */
  2845. Vector3.prototype.addInPlace = function (otherVector) {
  2846. this.x += otherVector.x;
  2847. this.y += otherVector.y;
  2848. this.z += otherVector.z;
  2849. return this;
  2850. };
  2851. /**
  2852. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2853. * @param otherVector defines the second operand
  2854. * @returns the resulting Vector3
  2855. */
  2856. Vector3.prototype.add = function (otherVector) {
  2857. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2858. };
  2859. /**
  2860. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2861. * @param otherVector defines the second operand
  2862. * @param result defines the Vector3 object where to store the result
  2863. * @returns the current Vector3
  2864. */
  2865. Vector3.prototype.addToRef = function (otherVector, result) {
  2866. result.x = this.x + otherVector.x;
  2867. result.y = this.y + otherVector.y;
  2868. result.z = this.z + otherVector.z;
  2869. return this;
  2870. };
  2871. /**
  2872. * Subtract the given vector from the current Vector3
  2873. * @param otherVector defines the second operand
  2874. * @returns the current updated Vector3
  2875. */
  2876. Vector3.prototype.subtractInPlace = function (otherVector) {
  2877. this.x -= otherVector.x;
  2878. this.y -= otherVector.y;
  2879. this.z -= otherVector.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2884. * @param otherVector defines the second operand
  2885. * @returns the resulting Vector3
  2886. */
  2887. Vector3.prototype.subtract = function (otherVector) {
  2888. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2889. };
  2890. /**
  2891. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2892. * @param otherVector defines the second operand
  2893. * @param result defines the Vector3 object where to store the result
  2894. * @returns the current Vector3
  2895. */
  2896. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2897. result.x = this.x - otherVector.x;
  2898. result.y = this.y - otherVector.y;
  2899. result.z = this.z - otherVector.z;
  2900. return this;
  2901. };
  2902. /**
  2903. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2904. * @param x defines the x coordinate of the operand
  2905. * @param y defines the y coordinate of the operand
  2906. * @param z defines the z coordinate of the operand
  2907. * @returns the resulting Vector3
  2908. */
  2909. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2910. return new Vector3(this.x - x, this.y - y, this.z - z);
  2911. };
  2912. /**
  2913. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2914. * @param x defines the x coordinate of the operand
  2915. * @param y defines the y coordinate of the operand
  2916. * @param z defines the z coordinate of the operand
  2917. * @param result defines the Vector3 object where to store the result
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2921. result.x = this.x - x;
  2922. result.y = this.y - y;
  2923. result.z = this.z - z;
  2924. return this;
  2925. };
  2926. /**
  2927. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2928. * @returns a new Vector3
  2929. */
  2930. Vector3.prototype.negate = function () {
  2931. return new Vector3(-this.x, -this.y, -this.z);
  2932. };
  2933. /**
  2934. * Multiplies the Vector3 coordinates by the float "scale"
  2935. * @param scale defines the multiplier factor
  2936. * @returns the current updated Vector3
  2937. */
  2938. Vector3.prototype.scaleInPlace = function (scale) {
  2939. this.x *= scale;
  2940. this.y *= scale;
  2941. this.z *= scale;
  2942. return this;
  2943. };
  2944. /**
  2945. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2946. * @param scale defines the multiplier factor
  2947. * @returns a new Vector3
  2948. */
  2949. Vector3.prototype.scale = function (scale) {
  2950. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2951. };
  2952. /**
  2953. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2954. * @param scale defines the multiplier factor
  2955. * @param result defines the Vector3 object where to store the result
  2956. * @returns the current Vector3
  2957. */
  2958. Vector3.prototype.scaleToRef = function (scale, result) {
  2959. result.x = this.x * scale;
  2960. result.y = this.y * scale;
  2961. result.z = this.z * scale;
  2962. return this;
  2963. };
  2964. /**
  2965. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2966. * @param scale defines the scale factor
  2967. * @param result defines the Vector3 object where to store the result
  2968. * @returns the unmodified current Vector3
  2969. */
  2970. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2971. result.x += this.x * scale;
  2972. result.y += this.y * scale;
  2973. result.z += this.z * scale;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2978. * @param otherVector defines the second operand
  2979. * @returns true if both vectors are equals
  2980. */
  2981. Vector3.prototype.equals = function (otherVector) {
  2982. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2983. };
  2984. /**
  2985. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2986. * @param otherVector defines the second operand
  2987. * @param epsilon defines the minimal distance to define values as equals
  2988. * @returns true if both vectors are distant less than epsilon
  2989. */
  2990. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2991. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2992. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2993. };
  2994. /**
  2995. * Returns true if the current Vector3 coordinates equals the given floats
  2996. * @param x defines the x coordinate of the operand
  2997. * @param y defines the y coordinate of the operand
  2998. * @param z defines the z coordinate of the operand
  2999. * @returns true if both vectors are equals
  3000. */
  3001. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3002. return this.x === x && this.y === y && this.z === z;
  3003. };
  3004. /**
  3005. * Multiplies the current Vector3 coordinates by the given ones
  3006. * @param otherVector defines the second operand
  3007. * @returns the current updated Vector3
  3008. */
  3009. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3010. this.x *= otherVector.x;
  3011. this.y *= otherVector.y;
  3012. this.z *= otherVector.z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3017. * @param otherVector defines the second operand
  3018. * @returns the new Vector3
  3019. */
  3020. Vector3.prototype.multiply = function (otherVector) {
  3021. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3022. };
  3023. /**
  3024. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3025. * @param otherVector defines the second operand
  3026. * @param result defines the Vector3 object where to store the result
  3027. * @returns the current Vector3
  3028. */
  3029. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3030. result.x = this.x * otherVector.x;
  3031. result.y = this.y * otherVector.y;
  3032. result.z = this.z * otherVector.z;
  3033. return this;
  3034. };
  3035. /**
  3036. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3037. * @param x defines the x coordinate of the operand
  3038. * @param y defines the y coordinate of the operand
  3039. * @param z defines the z coordinate of the operand
  3040. * @returns the new Vector3
  3041. */
  3042. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3043. return new Vector3(this.x * x, this.y * y, this.z * z);
  3044. };
  3045. /**
  3046. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3047. * @param otherVector defines the second operand
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.divide = function (otherVector) {
  3051. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3052. };
  3053. /**
  3054. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3055. * @param otherVector defines the second operand
  3056. * @param result defines the Vector3 object where to store the result
  3057. * @returns the current Vector3
  3058. */
  3059. Vector3.prototype.divideToRef = function (otherVector, result) {
  3060. result.x = this.x / otherVector.x;
  3061. result.y = this.y / otherVector.y;
  3062. result.z = this.z / otherVector.z;
  3063. return this;
  3064. };
  3065. /**
  3066. * Divides the current Vector3 coordinates by the given ones.
  3067. * @param otherVector defines the second operand
  3068. * @returns the current updated Vector3
  3069. */
  3070. Vector3.prototype.divideInPlace = function (otherVector) {
  3071. return this.divideToRef(otherVector, this);
  3072. };
  3073. /**
  3074. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3075. * @param other defines the second operand
  3076. * @returns the current updated Vector3
  3077. */
  3078. Vector3.prototype.minimizeInPlace = function (other) {
  3079. if (other.x < this.x)
  3080. this.x = other.x;
  3081. if (other.y < this.y)
  3082. this.y = other.y;
  3083. if (other.z < this.z)
  3084. this.z = other.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3089. * @param other defines the second operand
  3090. * @returns the current updated Vector3
  3091. */
  3092. Vector3.prototype.maximizeInPlace = function (other) {
  3093. if (other.x > this.x)
  3094. this.x = other.x;
  3095. if (other.y > this.y)
  3096. this.y = other.y;
  3097. if (other.z > this.z)
  3098. this.z = other.z;
  3099. return this;
  3100. };
  3101. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3102. /**
  3103. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3104. */
  3105. get: function () {
  3106. var absX = Math.abs(this.x);
  3107. var absY = Math.abs(this.y);
  3108. if (absX !== absY) {
  3109. return true;
  3110. }
  3111. var absZ = Math.abs(this.z);
  3112. if (absX !== absZ) {
  3113. return true;
  3114. }
  3115. if (absY !== absZ) {
  3116. return true;
  3117. }
  3118. return false;
  3119. },
  3120. enumerable: true,
  3121. configurable: true
  3122. });
  3123. // Properties
  3124. /**
  3125. * Gets the length of the Vector3
  3126. * @returns the length of the Vecto3
  3127. */
  3128. Vector3.prototype.length = function () {
  3129. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3130. };
  3131. /**
  3132. * Gets the squared length of the Vector3
  3133. * @returns squared length of the Vector3
  3134. */
  3135. Vector3.prototype.lengthSquared = function () {
  3136. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3137. };
  3138. /**
  3139. * Normalize the current Vector3.
  3140. * Please note that this is an in place operation.
  3141. * @returns the current updated Vector3
  3142. */
  3143. Vector3.prototype.normalize = function () {
  3144. var len = this.length();
  3145. if (len === 0 || len === 1.0)
  3146. return this;
  3147. var num = 1.0 / len;
  3148. this.x *= num;
  3149. this.y *= num;
  3150. this.z *= num;
  3151. return this;
  3152. };
  3153. /**
  3154. * Normalize the current Vector3 to a new vector
  3155. * @returns the new Vector3
  3156. */
  3157. Vector3.prototype.normalizeToNew = function () {
  3158. var normalized = new Vector3(0, 0, 0);
  3159. this.normalizeToRef(normalized);
  3160. return normalized;
  3161. };
  3162. /**
  3163. * Normalize the current Vector3 to the reference
  3164. * @param reference define the Vector3 to update
  3165. * @returns the updated Vector3
  3166. */
  3167. Vector3.prototype.normalizeToRef = function (reference) {
  3168. var len = this.length();
  3169. if (len === 0 || len === 1.0) {
  3170. reference.set(this.x, this.y, this.z);
  3171. return reference;
  3172. }
  3173. var scale = 1.0 / len;
  3174. this.scaleToRef(scale, reference);
  3175. return reference;
  3176. };
  3177. /**
  3178. * Creates a new Vector3 copied from the current Vector3
  3179. * @returns the new Vector3
  3180. */
  3181. Vector3.prototype.clone = function () {
  3182. return new Vector3(this.x, this.y, this.z);
  3183. };
  3184. /**
  3185. * Copies the given vector coordinates to the current Vector3 ones
  3186. * @param source defines the source Vector3
  3187. * @returns the current updated Vector3
  3188. */
  3189. Vector3.prototype.copyFrom = function (source) {
  3190. this.x = source.x;
  3191. this.y = source.y;
  3192. this.z = source.z;
  3193. return this;
  3194. };
  3195. /**
  3196. * Copies the given floats to the current Vector3 coordinates
  3197. * @param x defines the x coordinate of the operand
  3198. * @param y defines the y coordinate of the operand
  3199. * @param z defines the z coordinate of the operand
  3200. * @returns the current updated Vector3
  3201. */
  3202. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3203. this.x = x;
  3204. this.y = y;
  3205. this.z = z;
  3206. return this;
  3207. };
  3208. /**
  3209. * Copies the given floats to the current Vector3 coordinates
  3210. * @param x defines the x coordinate of the operand
  3211. * @param y defines the y coordinate of the operand
  3212. * @param z defines the z coordinate of the operand
  3213. * @returns the current updated Vector3
  3214. */
  3215. Vector3.prototype.set = function (x, y, z) {
  3216. return this.copyFromFloats(x, y, z);
  3217. };
  3218. // Statics
  3219. /**
  3220. * Get the clip factor between two vectors
  3221. * @param vector0 defines the first operand
  3222. * @param vector1 defines the second operand
  3223. * @param axis defines the axis to use
  3224. * @param size defines the size along the axis
  3225. * @returns the clip factor
  3226. */
  3227. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3228. var d0 = Vector3.Dot(vector0, axis) - size;
  3229. var d1 = Vector3.Dot(vector1, axis) - size;
  3230. var s = d0 / (d0 - d1);
  3231. return s;
  3232. };
  3233. /**
  3234. * Get angle between two vectors
  3235. * @param vector0 angle between vector0 and vector1
  3236. * @param vector1 angle between vector0 and vector1
  3237. * @param normal direction of the normal
  3238. * @return the angle between vector0 and vector1
  3239. */
  3240. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3241. var v0 = vector0.clone().normalize();
  3242. var v1 = vector1.clone().normalize();
  3243. var dot = Vector3.Dot(v0, v1);
  3244. var n = Vector3.Cross(v0, v1);
  3245. if (Vector3.Dot(n, normal) > 0) {
  3246. return Math.acos(dot);
  3247. }
  3248. return -Math.acos(dot);
  3249. };
  3250. /**
  3251. * Returns a new Vector3 set from the index "offset" of the given array
  3252. * @param array defines the source array
  3253. * @param offset defines the offset in the source array
  3254. * @returns the new Vector3
  3255. */
  3256. Vector3.FromArray = function (array, offset) {
  3257. if (!offset) {
  3258. offset = 0;
  3259. }
  3260. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3264. * This function is deprecated. Use FromArray instead
  3265. * @param array defines the source array
  3266. * @param offset defines the offset in the source array
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.FromFloatArray = function (array, offset) {
  3270. return Vector3.FromArray(array, offset);
  3271. };
  3272. /**
  3273. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3274. * @param array defines the source array
  3275. * @param offset defines the offset in the source array
  3276. * @param result defines the Vector3 where to store the result
  3277. */
  3278. Vector3.FromArrayToRef = function (array, offset, result) {
  3279. result.x = array[offset];
  3280. result.y = array[offset + 1];
  3281. result.z = array[offset + 2];
  3282. };
  3283. /**
  3284. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3285. * This function is deprecated. Use FromArrayToRef instead.
  3286. * @param array defines the source array
  3287. * @param offset defines the offset in the source array
  3288. * @param result defines the Vector3 where to store the result
  3289. */
  3290. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3291. return Vector3.FromArrayToRef(array, offset, result);
  3292. };
  3293. /**
  3294. * Sets the given vector "result" with the given floats.
  3295. * @param x defines the x coordinate of the source
  3296. * @param y defines the y coordinate of the source
  3297. * @param z defines the z coordinate of the source
  3298. * @param result defines the Vector3 where to store the result
  3299. */
  3300. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3301. result.x = x;
  3302. result.y = y;
  3303. result.z = z;
  3304. };
  3305. /**
  3306. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3307. * @returns a new empty Vector3
  3308. */
  3309. Vector3.Zero = function () {
  3310. return new Vector3(0.0, 0.0, 0.0);
  3311. };
  3312. /**
  3313. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3314. * @returns a new unit Vector3
  3315. */
  3316. Vector3.One = function () {
  3317. return new Vector3(1.0, 1.0, 1.0);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3321. * @returns a new up Vector3
  3322. */
  3323. Vector3.Up = function () {
  3324. return new Vector3(0.0, 1.0, 0.0);
  3325. };
  3326. /**
  3327. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3328. * @returns a new forward Vector3
  3329. */
  3330. Vector3.Forward = function () {
  3331. return new Vector3(0.0, 0.0, 1.0);
  3332. };
  3333. /**
  3334. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3335. * @returns a new right Vector3
  3336. */
  3337. Vector3.Right = function () {
  3338. return new Vector3(1.0, 0.0, 0.0);
  3339. };
  3340. /**
  3341. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3342. * @returns a new left Vector3
  3343. */
  3344. Vector3.Left = function () {
  3345. return new Vector3(-1.0, 0.0, 0.0);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3349. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3350. * @param vector defines the Vector3 to transform
  3351. * @param transformation defines the transformation matrix
  3352. * @returns the transformed Vector3
  3353. */
  3354. Vector3.TransformCoordinates = function (vector, transformation) {
  3355. var result = Vector3.Zero();
  3356. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3357. return result;
  3358. };
  3359. /**
  3360. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3361. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3362. * @param vector defines the Vector3 to transform
  3363. * @param transformation defines the transformation matrix
  3364. * @param result defines the Vector3 where to store the result
  3365. */
  3366. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3367. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3368. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3369. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3370. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3371. result.x = x / w;
  3372. result.y = y / w;
  3373. result.z = z / w;
  3374. };
  3375. /**
  3376. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3377. * This method computes tranformed coordinates only, not transformed direction vectors
  3378. * @param x define the x coordinate of the source vector
  3379. * @param y define the y coordinate of the source vector
  3380. * @param z define the z coordinate of the source vector
  3381. * @param transformation defines the transformation matrix
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3385. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3386. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3387. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3388. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3389. result.x = rx / rw;
  3390. result.y = ry / rw;
  3391. result.z = rz / rw;
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3395. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3396. * @param vector defines the Vector3 to transform
  3397. * @param transformation defines the transformation matrix
  3398. * @returns the new Vector3
  3399. */
  3400. Vector3.TransformNormal = function (vector, transformation) {
  3401. var result = Vector3.Zero();
  3402. Vector3.TransformNormalToRef(vector, transformation, result);
  3403. return result;
  3404. };
  3405. /**
  3406. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3407. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3408. * @param vector defines the Vector3 to transform
  3409. * @param transformation defines the transformation matrix
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3413. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3414. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3415. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3416. result.x = x;
  3417. result.y = y;
  3418. result.z = z;
  3419. };
  3420. /**
  3421. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3422. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3423. * @param x define the x coordinate of the source vector
  3424. * @param y define the y coordinate of the source vector
  3425. * @param z define the z coordinate of the source vector
  3426. * @param transformation defines the transformation matrix
  3427. * @param result defines the Vector3 where to store the result
  3428. */
  3429. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3430. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3431. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3432. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3436. * @param value1 defines the first control point
  3437. * @param value2 defines the second control point
  3438. * @param value3 defines the third control point
  3439. * @param value4 defines the fourth control point
  3440. * @param amount defines the amount on the spline to use
  3441. * @returns the new Vector3
  3442. */
  3443. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3444. var squared = amount * amount;
  3445. var cubed = amount * squared;
  3446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3452. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3453. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3454. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3455. return new Vector3(x, y, z);
  3456. };
  3457. /**
  3458. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3459. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3460. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3461. * @param value defines the current value
  3462. * @param min defines the lower range value
  3463. * @param max defines the upper range value
  3464. * @returns the new Vector3
  3465. */
  3466. Vector3.Clamp = function (value, min, max) {
  3467. var x = value.x;
  3468. x = (x > max.x) ? max.x : x;
  3469. x = (x < min.x) ? min.x : x;
  3470. var y = value.y;
  3471. y = (y > max.y) ? max.y : y;
  3472. y = (y < min.y) ? min.y : y;
  3473. var z = value.z;
  3474. z = (z > max.z) ? max.z : z;
  3475. z = (z < min.z) ? min.z : z;
  3476. return new Vector3(x, y, z);
  3477. };
  3478. /**
  3479. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3480. * @param value1 defines the first control point
  3481. * @param tangent1 defines the first tangent vector
  3482. * @param value2 defines the second control point
  3483. * @param tangent2 defines the second tangent vector
  3484. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3485. * @returns the new Vector3
  3486. */
  3487. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3488. var squared = amount * amount;
  3489. var cubed = amount * squared;
  3490. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3491. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3492. var part3 = (cubed - (2.0 * squared)) + amount;
  3493. var part4 = cubed - squared;
  3494. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3495. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3496. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3497. return new Vector3(x, y, z);
  3498. };
  3499. /**
  3500. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3501. * @param start defines the start value
  3502. * @param end defines the end value
  3503. * @param amount max defines amount between both (between 0 and 1)
  3504. * @returns the new Vector3
  3505. */
  3506. Vector3.Lerp = function (start, end, amount) {
  3507. var result = new Vector3(0, 0, 0);
  3508. Vector3.LerpToRef(start, end, amount, result);
  3509. return result;
  3510. };
  3511. /**
  3512. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3513. * @param start defines the start value
  3514. * @param end defines the end value
  3515. * @param amount max defines amount between both (between 0 and 1)
  3516. * @param result defines the Vector3 where to store the result
  3517. */
  3518. Vector3.LerpToRef = function (start, end, amount, result) {
  3519. result.x = start.x + ((end.x - start.x) * amount);
  3520. result.y = start.y + ((end.y - start.y) * amount);
  3521. result.z = start.z + ((end.z - start.z) * amount);
  3522. };
  3523. /**
  3524. * Returns the dot product (float) between the vectors "left" and "right"
  3525. * @param left defines the left operand
  3526. * @param right defines the right operand
  3527. * @returns the dot product
  3528. */
  3529. Vector3.Dot = function (left, right) {
  3530. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3531. };
  3532. /**
  3533. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3534. * The cross product is then orthogonal to both "left" and "right"
  3535. * @param left defines the left operand
  3536. * @param right defines the right operand
  3537. * @returns the cross product
  3538. */
  3539. Vector3.Cross = function (left, right) {
  3540. var result = Vector3.Zero();
  3541. Vector3.CrossToRef(left, right, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the given vector "result" with the cross product of "left" and "right"
  3546. * The cross product is then orthogonal to both "left" and "right"
  3547. * @param left defines the left operand
  3548. * @param right defines the right operand
  3549. * @param result defines the Vector3 where to store the result
  3550. */
  3551. Vector3.CrossToRef = function (left, right, result) {
  3552. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3553. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3554. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3555. result.copyFrom(MathTmp.Vector3[0]);
  3556. };
  3557. /**
  3558. * Returns a new Vector3 as the normalization of the given vector
  3559. * @param vector defines the Vector3 to normalize
  3560. * @returns the new Vector3
  3561. */
  3562. Vector3.Normalize = function (vector) {
  3563. var result = Vector3.Zero();
  3564. Vector3.NormalizeToRef(vector, result);
  3565. return result;
  3566. };
  3567. /**
  3568. * Sets the given vector "result" with the normalization of the given first vector
  3569. * @param vector defines the Vector3 to normalize
  3570. * @param result defines the Vector3 where to store the result
  3571. */
  3572. Vector3.NormalizeToRef = function (vector, result) {
  3573. result.copyFrom(vector);
  3574. result.normalize();
  3575. };
  3576. /**
  3577. * Project a Vector3 onto screen space
  3578. * @param vector defines the Vector3 to project
  3579. * @param world defines the world matrix to use
  3580. * @param transform defines the transform (view x projection) matrix to use
  3581. * @param viewport defines the screen viewport to use
  3582. * @returns the new Vector3
  3583. */
  3584. Vector3.Project = function (vector, world, transform, viewport) {
  3585. var cw = viewport.width;
  3586. var ch = viewport.height;
  3587. var cx = viewport.x;
  3588. var cy = viewport.y;
  3589. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3590. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3591. var matrix = MathTmp.Matrix[0];
  3592. world.multiplyToRef(transform, matrix);
  3593. matrix.multiplyToRef(viewportMatrix, matrix);
  3594. return Vector3.TransformCoordinates(vector, matrix);
  3595. };
  3596. /**
  3597. * Unproject from screen space to object space
  3598. * @param source defines the screen space Vector3 to use
  3599. * @param viewportWidth defines the current width of the viewport
  3600. * @param viewportHeight defines the current height of the viewport
  3601. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3602. * @param transform defines the transform (view x projection) matrix to use
  3603. * @returns the new Vector3
  3604. */
  3605. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3606. var matrix = MathTmp.Matrix[0];
  3607. world.multiplyToRef(transform, matrix);
  3608. matrix.invert();
  3609. source.x = source.x / viewportWidth * 2 - 1;
  3610. source.y = -(source.y / viewportHeight * 2 - 1);
  3611. var vector = Vector3.TransformCoordinates(source, matrix);
  3612. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3613. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3614. vector = vector.scale(1.0 / num);
  3615. }
  3616. return vector;
  3617. };
  3618. /**
  3619. * Unproject from screen space to object space
  3620. * @param source defines the screen space Vector3 to use
  3621. * @param viewportWidth defines the current width of the viewport
  3622. * @param viewportHeight defines the current height of the viewport
  3623. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3624. * @param view defines the view matrix to use
  3625. * @param projection defines the projection matrix to use
  3626. * @returns the new Vector3
  3627. */
  3628. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3629. var result = Vector3.Zero();
  3630. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Unproject from screen space to object space
  3635. * @param source defines the screen space Vector3 to use
  3636. * @param viewportWidth defines the current width of the viewport
  3637. * @param viewportHeight defines the current height of the viewport
  3638. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3639. * @param view defines the view matrix to use
  3640. * @param projection defines the projection matrix to use
  3641. * @param result defines the Vector3 where to store the result
  3642. */
  3643. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3644. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3645. };
  3646. /**
  3647. * Unproject from screen space to object space
  3648. * @param sourceX defines the screen space x coordinate to use
  3649. * @param sourceY defines the screen space y coordinate to use
  3650. * @param sourceZ defines the screen space z coordinate to use
  3651. * @param viewportWidth defines the current width of the viewport
  3652. * @param viewportHeight defines the current height of the viewport
  3653. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3654. * @param view defines the view matrix to use
  3655. * @param projection defines the projection matrix to use
  3656. * @param result defines the Vector3 where to store the result
  3657. */
  3658. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3659. var matrix = MathTmp.Matrix[0];
  3660. world.multiplyToRef(view, matrix);
  3661. matrix.multiplyToRef(projection, matrix);
  3662. matrix.invert();
  3663. var screenSource = MathTmp.Vector3[0];
  3664. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3665. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3666. screenSource.z = 2 * sourceZ - 1.0;
  3667. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3668. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3669. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3670. result.scaleInPlace(1.0 / num);
  3671. }
  3672. };
  3673. /**
  3674. * Gets the minimal coordinate values between two Vector3
  3675. * @param left defines the first operand
  3676. * @param right defines the second operand
  3677. * @returns the new Vector3
  3678. */
  3679. Vector3.Minimize = function (left, right) {
  3680. var min = left.clone();
  3681. min.minimizeInPlace(right);
  3682. return min;
  3683. };
  3684. /**
  3685. * Gets the maximal coordinate values between two Vector3
  3686. * @param left defines the first operand
  3687. * @param right defines the second operand
  3688. * @returns the new Vector3
  3689. */
  3690. Vector3.Maximize = function (left, right) {
  3691. var max = left.clone();
  3692. max.maximizeInPlace(right);
  3693. return max;
  3694. };
  3695. /**
  3696. * Returns the distance between the vectors "value1" and "value2"
  3697. * @param value1 defines the first operand
  3698. * @param value2 defines the second operand
  3699. * @returns the distance
  3700. */
  3701. Vector3.Distance = function (value1, value2) {
  3702. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3703. };
  3704. /**
  3705. * Returns the squared distance between the vectors "value1" and "value2"
  3706. * @param value1 defines the first operand
  3707. * @param value2 defines the second operand
  3708. * @returns the squared distance
  3709. */
  3710. Vector3.DistanceSquared = function (value1, value2) {
  3711. var x = value1.x - value2.x;
  3712. var y = value1.y - value2.y;
  3713. var z = value1.z - value2.z;
  3714. return (x * x) + (y * y) + (z * z);
  3715. };
  3716. /**
  3717. * Returns a new Vector3 located at the center between "value1" and "value2"
  3718. * @param value1 defines the first operand
  3719. * @param value2 defines the second operand
  3720. * @returns the new Vector3
  3721. */
  3722. Vector3.Center = function (value1, value2) {
  3723. var center = value1.add(value2);
  3724. center.scaleInPlace(0.5);
  3725. return center;
  3726. };
  3727. /**
  3728. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3729. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3730. * to something in order to rotate it from its local system to the given target system
  3731. * Note: axis1, axis2 and axis3 are normalized during this operation
  3732. * @param axis1 defines the first axis
  3733. * @param axis2 defines the second axis
  3734. * @param axis3 defines the third axis
  3735. * @returns a new Vector3
  3736. */
  3737. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3738. var rotation = Vector3.Zero();
  3739. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3740. return rotation;
  3741. };
  3742. /**
  3743. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3744. * @param axis1 defines the first axis
  3745. * @param axis2 defines the second axis
  3746. * @param axis3 defines the third axis
  3747. * @param ref defines the Vector3 where to store the result
  3748. */
  3749. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3750. var quat = MathTmp.Quaternion[0];
  3751. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3752. quat.toEulerAnglesToRef(ref);
  3753. };
  3754. return Vector3;
  3755. }());
  3756. BABYLON.Vector3 = Vector3;
  3757. //Vector4 class created for EulerAngle class conversion to Quaternion
  3758. var Vector4 = /** @class */ (function () {
  3759. /**
  3760. * Creates a Vector4 object from the given floats.
  3761. */
  3762. function Vector4(x, y, z, w) {
  3763. this.x = x;
  3764. this.y = y;
  3765. this.z = z;
  3766. this.w = w;
  3767. }
  3768. /**
  3769. * Returns the string with the Vector4 coordinates.
  3770. */
  3771. Vector4.prototype.toString = function () {
  3772. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3773. };
  3774. /**
  3775. * Returns the string "Vector4".
  3776. */
  3777. Vector4.prototype.getClassName = function () {
  3778. return "Vector4";
  3779. };
  3780. /**
  3781. * Returns the Vector4 hash code.
  3782. */
  3783. Vector4.prototype.getHashCode = function () {
  3784. var hash = this.x || 0;
  3785. hash = (hash * 397) ^ (this.y || 0);
  3786. hash = (hash * 397) ^ (this.z || 0);
  3787. hash = (hash * 397) ^ (this.w || 0);
  3788. return hash;
  3789. };
  3790. // Operators
  3791. /**
  3792. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3793. */
  3794. Vector4.prototype.asArray = function () {
  3795. var result = new Array();
  3796. this.toArray(result, 0);
  3797. return result;
  3798. };
  3799. /**
  3800. * Populates the given array from the given index with the Vector4 coordinates.
  3801. * Returns the Vector4.
  3802. */
  3803. Vector4.prototype.toArray = function (array, index) {
  3804. if (index === undefined) {
  3805. index = 0;
  3806. }
  3807. array[index] = this.x;
  3808. array[index + 1] = this.y;
  3809. array[index + 2] = this.z;
  3810. array[index + 3] = this.w;
  3811. return this;
  3812. };
  3813. /**
  3814. * Adds the given vector to the current Vector4.
  3815. * Returns the updated Vector4.
  3816. */
  3817. Vector4.prototype.addInPlace = function (otherVector) {
  3818. this.x += otherVector.x;
  3819. this.y += otherVector.y;
  3820. this.z += otherVector.z;
  3821. this.w += otherVector.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3826. */
  3827. Vector4.prototype.add = function (otherVector) {
  3828. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3829. };
  3830. /**
  3831. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3832. * Returns the current Vector4.
  3833. */
  3834. Vector4.prototype.addToRef = function (otherVector, result) {
  3835. result.x = this.x + otherVector.x;
  3836. result.y = this.y + otherVector.y;
  3837. result.z = this.z + otherVector.z;
  3838. result.w = this.w + otherVector.w;
  3839. return this;
  3840. };
  3841. /**
  3842. * Subtract in place the given vector from the current Vector4.
  3843. * Returns the updated Vector4.
  3844. */
  3845. Vector4.prototype.subtractInPlace = function (otherVector) {
  3846. this.x -= otherVector.x;
  3847. this.y -= otherVector.y;
  3848. this.z -= otherVector.z;
  3849. this.w -= otherVector.w;
  3850. return this;
  3851. };
  3852. /**
  3853. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3854. */
  3855. Vector4.prototype.subtract = function (otherVector) {
  3856. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3857. };
  3858. /**
  3859. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3860. * Returns the current Vector4.
  3861. */
  3862. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3863. result.x = this.x - otherVector.x;
  3864. result.y = this.y - otherVector.y;
  3865. result.z = this.z - otherVector.z;
  3866. result.w = this.w - otherVector.w;
  3867. return this;
  3868. };
  3869. /**
  3870. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3871. */
  3872. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3873. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3874. };
  3875. /**
  3876. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3877. * Returns the current Vector4.
  3878. */
  3879. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3880. result.x = this.x - x;
  3881. result.y = this.y - y;
  3882. result.z = this.z - z;
  3883. result.w = this.w - w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3888. */
  3889. Vector4.prototype.negate = function () {
  3890. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3891. };
  3892. /**
  3893. * Multiplies the current Vector4 coordinates by scale (float).
  3894. * Returns the updated Vector4.
  3895. */
  3896. Vector4.prototype.scaleInPlace = function (scale) {
  3897. this.x *= scale;
  3898. this.y *= scale;
  3899. this.z *= scale;
  3900. this.w *= scale;
  3901. return this;
  3902. };
  3903. /**
  3904. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3905. */
  3906. Vector4.prototype.scale = function (scale) {
  3907. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3908. };
  3909. /**
  3910. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3911. * Returns the current Vector4.
  3912. */
  3913. Vector4.prototype.scaleToRef = function (scale, result) {
  3914. result.x = this.x * scale;
  3915. result.y = this.y * scale;
  3916. result.z = this.z * scale;
  3917. result.w = this.w * scale;
  3918. return this;
  3919. };
  3920. /**
  3921. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3922. * @param scale defines the scale factor
  3923. * @param result defines the Vector4 object where to store the result
  3924. * @returns the unmodified current Vector4
  3925. */
  3926. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3927. result.x += this.x * scale;
  3928. result.y += this.y * scale;
  3929. result.z += this.z * scale;
  3930. result.w += this.w * scale;
  3931. return this;
  3932. };
  3933. /**
  3934. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3935. */
  3936. Vector4.prototype.equals = function (otherVector) {
  3937. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3938. };
  3939. /**
  3940. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3941. */
  3942. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3943. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3944. return otherVector
  3945. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3946. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3947. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3948. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3949. };
  3950. /**
  3951. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3952. */
  3953. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3954. return this.x === x && this.y === y && this.z === z && this.w === w;
  3955. };
  3956. /**
  3957. * Multiplies in place the current Vector4 by the given one.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3961. this.x *= otherVector.x;
  3962. this.y *= otherVector.y;
  3963. this.z *= otherVector.z;
  3964. this.w *= otherVector.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3969. */
  3970. Vector4.prototype.multiply = function (otherVector) {
  3971. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3972. };
  3973. /**
  3974. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3975. * Returns the current Vector4.
  3976. */
  3977. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3978. result.x = this.x * otherVector.x;
  3979. result.y = this.y * otherVector.y;
  3980. result.z = this.z * otherVector.z;
  3981. result.w = this.w * otherVector.w;
  3982. return this;
  3983. };
  3984. /**
  3985. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3986. */
  3987. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3988. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3989. };
  3990. /**
  3991. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3992. */
  3993. Vector4.prototype.divide = function (otherVector) {
  3994. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3995. };
  3996. /**
  3997. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3998. * Returns the current Vector4.
  3999. */
  4000. Vector4.prototype.divideToRef = function (otherVector, result) {
  4001. result.x = this.x / otherVector.x;
  4002. result.y = this.y / otherVector.y;
  4003. result.z = this.z / otherVector.z;
  4004. result.w = this.w / otherVector.w;
  4005. return this;
  4006. };
  4007. /**
  4008. * Divides the current Vector3 coordinates by the given ones.
  4009. * @returns the updated Vector3.
  4010. */
  4011. Vector4.prototype.divideInPlace = function (otherVector) {
  4012. return this.divideToRef(otherVector, this);
  4013. };
  4014. /**
  4015. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4016. * @param other defines the second operand
  4017. * @returns the current updated Vector4
  4018. */
  4019. Vector4.prototype.minimizeInPlace = function (other) {
  4020. if (other.x < this.x)
  4021. this.x = other.x;
  4022. if (other.y < this.y)
  4023. this.y = other.y;
  4024. if (other.z < this.z)
  4025. this.z = other.z;
  4026. if (other.w < this.w)
  4027. this.w = other.w;
  4028. return this;
  4029. };
  4030. /**
  4031. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4032. * @param other defines the second operand
  4033. * @returns the current updated Vector4
  4034. */
  4035. Vector4.prototype.maximizeInPlace = function (other) {
  4036. if (other.x > this.x)
  4037. this.x = other.x;
  4038. if (other.y > this.y)
  4039. this.y = other.y;
  4040. if (other.z > this.z)
  4041. this.z = other.z;
  4042. if (other.w > this.w)
  4043. this.w = other.w;
  4044. return this;
  4045. };
  4046. // Properties
  4047. /**
  4048. * Returns the Vector4 length (float).
  4049. */
  4050. Vector4.prototype.length = function () {
  4051. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4052. };
  4053. /**
  4054. * Returns the Vector4 squared length (float).
  4055. */
  4056. Vector4.prototype.lengthSquared = function () {
  4057. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4058. };
  4059. // Methods
  4060. /**
  4061. * Normalizes in place the Vector4.
  4062. * Returns the updated Vector4.
  4063. */
  4064. Vector4.prototype.normalize = function () {
  4065. var len = this.length();
  4066. if (len === 0)
  4067. return this;
  4068. var num = 1.0 / len;
  4069. this.x *= num;
  4070. this.y *= num;
  4071. this.z *= num;
  4072. this.w *= num;
  4073. return this;
  4074. };
  4075. /**
  4076. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4077. */
  4078. Vector4.prototype.toVector3 = function () {
  4079. return new Vector3(this.x, this.y, this.z);
  4080. };
  4081. /**
  4082. * Returns a new Vector4 copied from the current one.
  4083. */
  4084. Vector4.prototype.clone = function () {
  4085. return new Vector4(this.x, this.y, this.z, this.w);
  4086. };
  4087. /**
  4088. * Updates the current Vector4 with the given one coordinates.
  4089. * Returns the updated Vector4.
  4090. */
  4091. Vector4.prototype.copyFrom = function (source) {
  4092. this.x = source.x;
  4093. this.y = source.y;
  4094. this.z = source.z;
  4095. this.w = source.w;
  4096. return this;
  4097. };
  4098. /**
  4099. * Updates the current Vector4 coordinates with the given floats.
  4100. * Returns the updated Vector4.
  4101. */
  4102. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4103. this.x = x;
  4104. this.y = y;
  4105. this.z = z;
  4106. this.w = w;
  4107. return this;
  4108. };
  4109. /**
  4110. * Updates the current Vector4 coordinates with the given floats.
  4111. * Returns the updated Vector4.
  4112. */
  4113. Vector4.prototype.set = function (x, y, z, w) {
  4114. return this.copyFromFloats(x, y, z, w);
  4115. };
  4116. // Statics
  4117. /**
  4118. * Returns a new Vector4 set from the starting index of the given array.
  4119. */
  4120. Vector4.FromArray = function (array, offset) {
  4121. if (!offset) {
  4122. offset = 0;
  4123. }
  4124. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4125. };
  4126. /**
  4127. * Updates the given vector "result" from the starting index of the given array.
  4128. */
  4129. Vector4.FromArrayToRef = function (array, offset, result) {
  4130. result.x = array[offset];
  4131. result.y = array[offset + 1];
  4132. result.z = array[offset + 2];
  4133. result.w = array[offset + 3];
  4134. };
  4135. /**
  4136. * Updates the given vector "result" from the starting index of the given Float32Array.
  4137. */
  4138. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4139. Vector4.FromArrayToRef(array, offset, result);
  4140. };
  4141. /**
  4142. * Updates the given vector "result" coordinates from the given floats.
  4143. */
  4144. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4145. result.x = x;
  4146. result.y = y;
  4147. result.z = z;
  4148. result.w = w;
  4149. };
  4150. /**
  4151. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4152. */
  4153. Vector4.Zero = function () {
  4154. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4155. };
  4156. /**
  4157. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4158. */
  4159. Vector4.One = function () {
  4160. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4161. };
  4162. /**
  4163. * Returns a new normalized Vector4 from the given one.
  4164. */
  4165. Vector4.Normalize = function (vector) {
  4166. var result = Vector4.Zero();
  4167. Vector4.NormalizeToRef(vector, result);
  4168. return result;
  4169. };
  4170. /**
  4171. * Updates the given vector "result" from the normalization of the given one.
  4172. */
  4173. Vector4.NormalizeToRef = function (vector, result) {
  4174. result.copyFrom(vector);
  4175. result.normalize();
  4176. };
  4177. Vector4.Minimize = function (left, right) {
  4178. var min = left.clone();
  4179. min.minimizeInPlace(right);
  4180. return min;
  4181. };
  4182. Vector4.Maximize = function (left, right) {
  4183. var max = left.clone();
  4184. max.maximizeInPlace(right);
  4185. return max;
  4186. };
  4187. /**
  4188. * Returns the distance (float) between the vectors "value1" and "value2".
  4189. */
  4190. Vector4.Distance = function (value1, value2) {
  4191. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4192. };
  4193. /**
  4194. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4195. */
  4196. Vector4.DistanceSquared = function (value1, value2) {
  4197. var x = value1.x - value2.x;
  4198. var y = value1.y - value2.y;
  4199. var z = value1.z - value2.z;
  4200. var w = value1.w - value2.w;
  4201. return (x * x) + (y * y) + (z * z) + (w * w);
  4202. };
  4203. /**
  4204. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4205. */
  4206. Vector4.Center = function (value1, value2) {
  4207. var center = value1.add(value2);
  4208. center.scaleInPlace(0.5);
  4209. return center;
  4210. };
  4211. /**
  4212. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4213. * This methods computes transformed normalized direction vectors only.
  4214. */
  4215. Vector4.TransformNormal = function (vector, transformation) {
  4216. var result = Vector4.Zero();
  4217. Vector4.TransformNormalToRef(vector, transformation, result);
  4218. return result;
  4219. };
  4220. /**
  4221. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4222. * This methods computes transformed normalized direction vectors only.
  4223. */
  4224. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4225. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4226. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4227. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4228. result.x = x;
  4229. result.y = y;
  4230. result.z = z;
  4231. result.w = vector.w;
  4232. };
  4233. /**
  4234. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4235. * This methods computes transformed normalized direction vectors only.
  4236. */
  4237. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4238. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4239. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4240. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4241. result.w = w;
  4242. };
  4243. return Vector4;
  4244. }());
  4245. BABYLON.Vector4 = Vector4;
  4246. var Size = /** @class */ (function () {
  4247. /**
  4248. * Creates a Size object from the given width and height (floats).
  4249. */
  4250. function Size(width, height) {
  4251. this.width = width;
  4252. this.height = height;
  4253. }
  4254. // Returns a string with the Size width and height.
  4255. Size.prototype.toString = function () {
  4256. return "{W: " + this.width + ", H: " + this.height + "}";
  4257. };
  4258. /**
  4259. * Returns the string "Size"
  4260. */
  4261. Size.prototype.getClassName = function () {
  4262. return "Size";
  4263. };
  4264. /**
  4265. * Returns the Size hash code.
  4266. */
  4267. Size.prototype.getHashCode = function () {
  4268. var hash = this.width || 0;
  4269. hash = (hash * 397) ^ (this.height || 0);
  4270. return hash;
  4271. };
  4272. /**
  4273. * Updates the current size from the given one.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFrom = function (src) {
  4277. this.width = src.width;
  4278. this.height = src.height;
  4279. };
  4280. /**
  4281. * Updates in place the current Size from the given floats.
  4282. * Returns the updated Size.
  4283. */
  4284. Size.prototype.copyFromFloats = function (width, height) {
  4285. this.width = width;
  4286. this.height = height;
  4287. return this;
  4288. };
  4289. /**
  4290. * Updates in place the current Size from the given floats.
  4291. * Returns the updated Size.
  4292. */
  4293. Size.prototype.set = function (width, height) {
  4294. return this.copyFromFloats(width, height);
  4295. };
  4296. /**
  4297. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4298. */
  4299. Size.prototype.multiplyByFloats = function (w, h) {
  4300. return new Size(this.width * w, this.height * h);
  4301. };
  4302. /**
  4303. * Returns a new Size copied from the given one.
  4304. */
  4305. Size.prototype.clone = function () {
  4306. return new Size(this.width, this.height);
  4307. };
  4308. /**
  4309. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4310. */
  4311. Size.prototype.equals = function (other) {
  4312. if (!other) {
  4313. return false;
  4314. }
  4315. return (this.width === other.width) && (this.height === other.height);
  4316. };
  4317. Object.defineProperty(Size.prototype, "surface", {
  4318. /**
  4319. * Returns the surface of the Size : width * height (float).
  4320. */
  4321. get: function () {
  4322. return this.width * this.height;
  4323. },
  4324. enumerable: true,
  4325. configurable: true
  4326. });
  4327. /**
  4328. * Returns a new Size set to (0.0, 0.0)
  4329. */
  4330. Size.Zero = function () {
  4331. return new Size(0.0, 0.0);
  4332. };
  4333. /**
  4334. * Returns a new Size set as the addition result of the current Size and the given one.
  4335. */
  4336. Size.prototype.add = function (otherSize) {
  4337. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4338. return r;
  4339. };
  4340. /**
  4341. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4342. */
  4343. Size.prototype.subtract = function (otherSize) {
  4344. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4345. return r;
  4346. };
  4347. /**
  4348. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4349. */
  4350. Size.Lerp = function (start, end, amount) {
  4351. var w = start.width + ((end.width - start.width) * amount);
  4352. var h = start.height + ((end.height - start.height) * amount);
  4353. return new Size(w, h);
  4354. };
  4355. return Size;
  4356. }());
  4357. BABYLON.Size = Size;
  4358. /**
  4359. * Class used to store quaternion data
  4360. * @see https://en.wikipedia.org/wiki/Quaternion
  4361. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4362. */
  4363. var Quaternion = /** @class */ (function () {
  4364. /**
  4365. * Creates a new Quaternion from the given floats
  4366. * @param x defines the first component (0 by default)
  4367. * @param y defines the second component (0 by default)
  4368. * @param z defines the third component (0 by default)
  4369. * @param w defines the fourth component (1.0 by default)
  4370. */
  4371. function Quaternion(
  4372. /** defines the first component (0 by default) */
  4373. x,
  4374. /** defines the second component (0 by default) */
  4375. y,
  4376. /** defines the third component (0 by default) */
  4377. z,
  4378. /** defines the fourth component (1.0 by default) */
  4379. w) {
  4380. if (x === void 0) { x = 0.0; }
  4381. if (y === void 0) { y = 0.0; }
  4382. if (z === void 0) { z = 0.0; }
  4383. if (w === void 0) { w = 1.0; }
  4384. this.x = x;
  4385. this.y = y;
  4386. this.z = z;
  4387. this.w = w;
  4388. }
  4389. /**
  4390. * Gets a string representation for the current quaternion
  4391. * @returns a string with the Quaternion coordinates
  4392. */
  4393. Quaternion.prototype.toString = function () {
  4394. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4395. };
  4396. /**
  4397. * Gets the class name of the quaternion
  4398. * @returns the string "Quaternion"
  4399. */
  4400. Quaternion.prototype.getClassName = function () {
  4401. return "Quaternion";
  4402. };
  4403. /**
  4404. * Gets a hash code for this quaternion
  4405. * @returns the quaternion hash code
  4406. */
  4407. Quaternion.prototype.getHashCode = function () {
  4408. var hash = this.x || 0;
  4409. hash = (hash * 397) ^ (this.y || 0);
  4410. hash = (hash * 397) ^ (this.z || 0);
  4411. hash = (hash * 397) ^ (this.w || 0);
  4412. return hash;
  4413. };
  4414. /**
  4415. * Copy the quaternion to an array
  4416. * @returns a new array populated with 4 elements from the quaternion coordinates
  4417. */
  4418. Quaternion.prototype.asArray = function () {
  4419. return [this.x, this.y, this.z, this.w];
  4420. };
  4421. /**
  4422. * Check if two quaternions are equals
  4423. * @param otherQuaternion defines the second operand
  4424. * @return true if the current quaternion and the given one coordinates are strictly equals
  4425. */
  4426. Quaternion.prototype.equals = function (otherQuaternion) {
  4427. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4428. };
  4429. /**
  4430. * Clone the current quaternion
  4431. * @returns a new quaternion copied from the current one
  4432. */
  4433. Quaternion.prototype.clone = function () {
  4434. return new Quaternion(this.x, this.y, this.z, this.w);
  4435. };
  4436. /**
  4437. * Copy a quaternion to the current one
  4438. * @param other defines the other quaternion
  4439. * @returns the updated current quaternion
  4440. */
  4441. Quaternion.prototype.copyFrom = function (other) {
  4442. this.x = other.x;
  4443. this.y = other.y;
  4444. this.z = other.z;
  4445. this.w = other.w;
  4446. return this;
  4447. };
  4448. /**
  4449. * Updates the current quaternion with the given float coordinates
  4450. * @param x defines the x coordinate
  4451. * @param y defines the y coordinate
  4452. * @param z defines the z coordinate
  4453. * @param w defines the w coordinate
  4454. * @returns the updated current quaternion
  4455. */
  4456. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4457. this.x = x;
  4458. this.y = y;
  4459. this.z = z;
  4460. this.w = w;
  4461. return this;
  4462. };
  4463. /**
  4464. * Updates the current quaternion from the given float coordinates
  4465. * @param x defines the x coordinate
  4466. * @param y defines the y coordinate
  4467. * @param z defines the z coordinate
  4468. * @param w defines the w coordinate
  4469. * @returns the updated current quaternion
  4470. */
  4471. Quaternion.prototype.set = function (x, y, z, w) {
  4472. return this.copyFromFloats(x, y, z, w);
  4473. };
  4474. /**
  4475. * Adds two quaternions
  4476. * @param other defines the second operand
  4477. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4478. */
  4479. Quaternion.prototype.add = function (other) {
  4480. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4481. };
  4482. /**
  4483. * Add a quaternion to the current one
  4484. * @param other defines the quaternion to add
  4485. * @returns the current quaternion
  4486. */
  4487. Quaternion.prototype.addInPlace = function (other) {
  4488. this.x += other.x;
  4489. this.y += other.y;
  4490. this.z += other.z;
  4491. this.w += other.w;
  4492. return this;
  4493. };
  4494. /**
  4495. * Subtract two quaternions
  4496. * @param other defines the second operand
  4497. * @returns a new quaternion as the subtraction result of the given one from the current one
  4498. */
  4499. Quaternion.prototype.subtract = function (other) {
  4500. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4501. };
  4502. /**
  4503. * Multiplies the current quaternion by a scale factor
  4504. * @param value defines the scale factor
  4505. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4506. */
  4507. Quaternion.prototype.scale = function (value) {
  4508. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4509. };
  4510. /**
  4511. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4512. * @param scale defines the scale factor
  4513. * @param result defines the Quaternion object where to store the result
  4514. * @returns the unmodified current quaternion
  4515. */
  4516. Quaternion.prototype.scaleToRef = function (scale, result) {
  4517. result.x = this.x * scale;
  4518. result.y = this.y * scale;
  4519. result.z = this.z * scale;
  4520. result.w = this.w * scale;
  4521. return this;
  4522. };
  4523. /**
  4524. * Multiplies in place the current quaternion by a scale factor
  4525. * @param value defines the scale factor
  4526. * @returns the current modified quaternion
  4527. */
  4528. Quaternion.prototype.scaleInPlace = function (value) {
  4529. this.x *= value;
  4530. this.y *= value;
  4531. this.z *= value;
  4532. this.w *= value;
  4533. return this;
  4534. };
  4535. /**
  4536. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4537. * @param scale defines the scale factor
  4538. * @param result defines the Quaternion object where to store the result
  4539. * @returns the unmodified current quaternion
  4540. */
  4541. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4542. result.x += this.x * scale;
  4543. result.y += this.y * scale;
  4544. result.z += this.z * scale;
  4545. result.w += this.w * scale;
  4546. return this;
  4547. };
  4548. /**
  4549. * Multiplies two quaternions
  4550. * @param q1 defines the second operand
  4551. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4552. */
  4553. Quaternion.prototype.multiply = function (q1) {
  4554. var result = new Quaternion(0, 0, 0, 1.0);
  4555. this.multiplyToRef(q1, result);
  4556. return result;
  4557. };
  4558. /**
  4559. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4560. * @param q1 defines the second operand
  4561. * @param result defines the target quaternion
  4562. * @returns the current quaternion
  4563. */
  4564. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4565. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4566. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4567. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4568. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4569. result.copyFromFloats(x, y, z, w);
  4570. return this;
  4571. };
  4572. /**
  4573. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4574. * @param q1 defines the second operand
  4575. * @returns the currentupdated quaternion
  4576. */
  4577. Quaternion.prototype.multiplyInPlace = function (q1) {
  4578. this.multiplyToRef(q1, this);
  4579. return this;
  4580. };
  4581. /**
  4582. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4583. * @param ref defines the target quaternion
  4584. * @returns the current quaternion
  4585. */
  4586. Quaternion.prototype.conjugateToRef = function (ref) {
  4587. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4588. return this;
  4589. };
  4590. /**
  4591. * Conjugates in place (1-q) the current quaternion
  4592. * @returns the current updated quaternion
  4593. */
  4594. Quaternion.prototype.conjugateInPlace = function () {
  4595. this.x *= -1;
  4596. this.y *= -1;
  4597. this.z *= -1;
  4598. return this;
  4599. };
  4600. /**
  4601. * Conjugates in place (1-q) the current quaternion
  4602. * @returns a new quaternion
  4603. */
  4604. Quaternion.prototype.conjugate = function () {
  4605. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4606. return result;
  4607. };
  4608. /**
  4609. * Gets length of current quaternion
  4610. * @returns the quaternion length (float)
  4611. */
  4612. Quaternion.prototype.length = function () {
  4613. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4614. };
  4615. /**
  4616. * Normalize in place the current quaternion
  4617. * @returns the current updated quaternion
  4618. */
  4619. Quaternion.prototype.normalize = function () {
  4620. var length = 1.0 / this.length();
  4621. this.x *= length;
  4622. this.y *= length;
  4623. this.z *= length;
  4624. this.w *= length;
  4625. return this;
  4626. };
  4627. /**
  4628. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4629. * @param order is a reserved parameter and is ignore for now
  4630. * @returns a new Vector3 containing the Euler angles
  4631. */
  4632. Quaternion.prototype.toEulerAngles = function (order) {
  4633. if (order === void 0) { order = "YZX"; }
  4634. var result = Vector3.Zero();
  4635. this.toEulerAnglesToRef(result, order);
  4636. return result;
  4637. };
  4638. /**
  4639. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4640. * @param result defines the vector which will be filled with the Euler angles
  4641. * @param order is a reserved parameter and is ignore for now
  4642. * @returns the current unchanged quaternion
  4643. */
  4644. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4645. if (order === void 0) { order = "YZX"; }
  4646. var qz = this.z;
  4647. var qx = this.x;
  4648. var qy = this.y;
  4649. var qw = this.w;
  4650. var sqw = qw * qw;
  4651. var sqz = qz * qz;
  4652. var sqx = qx * qx;
  4653. var sqy = qy * qy;
  4654. var zAxisY = qy * qz - qx * qw;
  4655. var limit = .4999999;
  4656. if (zAxisY < -limit) {
  4657. result.y = 2 * Math.atan2(qy, qw);
  4658. result.x = Math.PI / 2;
  4659. result.z = 0;
  4660. }
  4661. else if (zAxisY > limit) {
  4662. result.y = 2 * Math.atan2(qy, qw);
  4663. result.x = -Math.PI / 2;
  4664. result.z = 0;
  4665. }
  4666. else {
  4667. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4668. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4669. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4670. }
  4671. return this;
  4672. };
  4673. /**
  4674. * Updates the given rotation matrix with the current quaternion values
  4675. * @param result defines the target matrix
  4676. * @returns the current unchanged quaternion
  4677. */
  4678. Quaternion.prototype.toRotationMatrix = function (result) {
  4679. var xx = this.x * this.x;
  4680. var yy = this.y * this.y;
  4681. var zz = this.z * this.z;
  4682. var xy = this.x * this.y;
  4683. var zw = this.z * this.w;
  4684. var zx = this.z * this.x;
  4685. var yw = this.y * this.w;
  4686. var yz = this.y * this.z;
  4687. var xw = this.x * this.w;
  4688. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4689. result.m[1] = 2.0 * (xy + zw);
  4690. result.m[2] = 2.0 * (zx - yw);
  4691. result.m[3] = 0;
  4692. result.m[4] = 2.0 * (xy - zw);
  4693. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4694. result.m[6] = 2.0 * (yz + xw);
  4695. result.m[7] = 0;
  4696. result.m[8] = 2.0 * (zx + yw);
  4697. result.m[9] = 2.0 * (yz - xw);
  4698. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4699. result.m[11] = 0;
  4700. result.m[12] = 0;
  4701. result.m[13] = 0;
  4702. result.m[14] = 0;
  4703. result.m[15] = 1.0;
  4704. result._markAsUpdated();
  4705. return this;
  4706. };
  4707. /**
  4708. * Updates the current quaternion from the given rotation matrix values
  4709. * @param matrix defines the source matrix
  4710. * @returns the current updated quaternion
  4711. */
  4712. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4713. Quaternion.FromRotationMatrixToRef(matrix, this);
  4714. return this;
  4715. };
  4716. // Statics
  4717. /**
  4718. * Creates a new quaternion from a rotation matrix
  4719. * @param matrix defines the source matrix
  4720. * @returns a new quaternion created from the given rotation matrix values
  4721. */
  4722. Quaternion.FromRotationMatrix = function (matrix) {
  4723. var result = new Quaternion();
  4724. Quaternion.FromRotationMatrixToRef(matrix, result);
  4725. return result;
  4726. };
  4727. /**
  4728. * Updates the given quaternion with the given rotation matrix values
  4729. * @param matrix defines the source matrix
  4730. * @param result defines the target quaternion
  4731. */
  4732. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4733. var data = matrix.m;
  4734. var m11 = data[0], m12 = data[4], m13 = data[8];
  4735. var m21 = data[1], m22 = data[5], m23 = data[9];
  4736. var m31 = data[2], m32 = data[6], m33 = data[10];
  4737. var trace = m11 + m22 + m33;
  4738. var s;
  4739. if (trace > 0) {
  4740. s = 0.5 / Math.sqrt(trace + 1.0);
  4741. result.w = 0.25 / s;
  4742. result.x = (m32 - m23) * s;
  4743. result.y = (m13 - m31) * s;
  4744. result.z = (m21 - m12) * s;
  4745. }
  4746. else if (m11 > m22 && m11 > m33) {
  4747. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4748. result.w = (m32 - m23) / s;
  4749. result.x = 0.25 * s;
  4750. result.y = (m12 + m21) / s;
  4751. result.z = (m13 + m31) / s;
  4752. }
  4753. else if (m22 > m33) {
  4754. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4755. result.w = (m13 - m31) / s;
  4756. result.x = (m12 + m21) / s;
  4757. result.y = 0.25 * s;
  4758. result.z = (m23 + m32) / s;
  4759. }
  4760. else {
  4761. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4762. result.w = (m21 - m12) / s;
  4763. result.x = (m13 + m31) / s;
  4764. result.y = (m23 + m32) / s;
  4765. result.z = 0.25 * s;
  4766. }
  4767. };
  4768. /**
  4769. * Creates an empty quaternion
  4770. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4771. */
  4772. Quaternion.Zero = function () {
  4773. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4774. };
  4775. /**
  4776. * Inverse a given quaternion
  4777. * @param q defines the source quaternion
  4778. * @returns a new quaternion as the inverted current quaternion
  4779. */
  4780. Quaternion.Inverse = function (q) {
  4781. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4782. };
  4783. /**
  4784. * Creates an identity quaternion
  4785. * @returns the identity quaternion
  4786. */
  4787. Quaternion.Identity = function () {
  4788. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4789. };
  4790. /**
  4791. * Gets a boolean indicating if the given quaternion is identity
  4792. * @param quaternion defines the quaternion to check
  4793. * @returns true if the quaternion is identity
  4794. */
  4795. Quaternion.IsIdentity = function (quaternion) {
  4796. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4797. };
  4798. /**
  4799. * Creates a quaternion from a rotation around an axis
  4800. * @param axis defines the axis to use
  4801. * @param angle defines the angle to use
  4802. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4803. */
  4804. Quaternion.RotationAxis = function (axis, angle) {
  4805. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4806. };
  4807. /**
  4808. * Creates a rotation around an axis and stores it into the given quaternion
  4809. * @param axis defines the axis to use
  4810. * @param angle defines the angle to use
  4811. * @param result defines the target quaternion
  4812. * @returns the target quaternion
  4813. */
  4814. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4815. var sin = Math.sin(angle / 2);
  4816. axis.normalize();
  4817. result.w = Math.cos(angle / 2);
  4818. result.x = axis.x * sin;
  4819. result.y = axis.y * sin;
  4820. result.z = axis.z * sin;
  4821. return result;
  4822. };
  4823. /**
  4824. * Creates a new quaternion from data stored into an array
  4825. * @param array defines the data source
  4826. * @param offset defines the offset in the source array where the data starts
  4827. * @returns a new quaternion
  4828. */
  4829. Quaternion.FromArray = function (array, offset) {
  4830. if (!offset) {
  4831. offset = 0;
  4832. }
  4833. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4834. };
  4835. /**
  4836. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4837. * @param yaw defines the rotation around Y axis
  4838. * @param pitch defines the rotation around X axis
  4839. * @param roll defines the rotation around Z axis
  4840. * @returns the new quaternion
  4841. */
  4842. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4843. var q = new Quaternion();
  4844. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4845. return q;
  4846. };
  4847. /**
  4848. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4849. * @param yaw defines the rotation around Y axis
  4850. * @param pitch defines the rotation around X axis
  4851. * @param roll defines the rotation around Z axis
  4852. * @param result defines the target quaternion
  4853. */
  4854. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4855. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4856. var halfRoll = roll * 0.5;
  4857. var halfPitch = pitch * 0.5;
  4858. var halfYaw = yaw * 0.5;
  4859. var sinRoll = Math.sin(halfRoll);
  4860. var cosRoll = Math.cos(halfRoll);
  4861. var sinPitch = Math.sin(halfPitch);
  4862. var cosPitch = Math.cos(halfPitch);
  4863. var sinYaw = Math.sin(halfYaw);
  4864. var cosYaw = Math.cos(halfYaw);
  4865. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4866. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4867. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4868. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4869. };
  4870. /**
  4871. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4872. * @param alpha defines the rotation around first axis
  4873. * @param beta defines the rotation around second axis
  4874. * @param gamma defines the rotation around third axis
  4875. * @returns the new quaternion
  4876. */
  4877. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4878. var result = new Quaternion();
  4879. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4880. return result;
  4881. };
  4882. /**
  4883. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4884. * @param alpha defines the rotation around first axis
  4885. * @param beta defines the rotation around second axis
  4886. * @param gamma defines the rotation around third axis
  4887. * @param result defines the target quaternion
  4888. */
  4889. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4890. // Produces a quaternion from Euler angles in the z-x-z orientation
  4891. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4892. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4893. var halfBeta = beta * 0.5;
  4894. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4895. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4896. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4897. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4898. };
  4899. /**
  4900. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4901. * @param axis1 defines the first axis
  4902. * @param axis2 defines the second axis
  4903. * @param axis3 defines the third axis
  4904. * @returns the new quaternion
  4905. */
  4906. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4907. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4908. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4909. return quat;
  4910. };
  4911. /**
  4912. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4913. * @param axis1 defines the first axis
  4914. * @param axis2 defines the second axis
  4915. * @param axis3 defines the third axis
  4916. * @param ref defines the target quaternion
  4917. */
  4918. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4919. var rotMat = MathTmp.Matrix[0];
  4920. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4921. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4922. };
  4923. /**
  4924. * Interpolates between two quaternions
  4925. * @param left defines first quaternion
  4926. * @param right defines second quaternion
  4927. * @param amount defines the gradient to use
  4928. * @returns the new interpolated quaternion
  4929. */
  4930. Quaternion.Slerp = function (left, right, amount) {
  4931. var result = Quaternion.Identity();
  4932. Quaternion.SlerpToRef(left, right, amount, result);
  4933. return result;
  4934. };
  4935. /**
  4936. * Interpolates between two quaternions and stores it into a target quaternion
  4937. * @param left defines first quaternion
  4938. * @param right defines second quaternion
  4939. * @param amount defines the gradient to use
  4940. * @param result defines the target quaternion
  4941. */
  4942. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4943. var num2;
  4944. var num3;
  4945. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4946. var flag = false;
  4947. if (num4 < 0) {
  4948. flag = true;
  4949. num4 = -num4;
  4950. }
  4951. if (num4 > 0.999999) {
  4952. num3 = 1 - amount;
  4953. num2 = flag ? -amount : amount;
  4954. }
  4955. else {
  4956. var num5 = Math.acos(num4);
  4957. var num6 = (1.0 / Math.sin(num5));
  4958. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4959. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4960. }
  4961. result.x = (num3 * left.x) + (num2 * right.x);
  4962. result.y = (num3 * left.y) + (num2 * right.y);
  4963. result.z = (num3 * left.z) + (num2 * right.z);
  4964. result.w = (num3 * left.w) + (num2 * right.w);
  4965. };
  4966. /**
  4967. * Interpolate between two quaternions using Hermite interpolation
  4968. * @param value1 defines first quaternion
  4969. * @param tangent1 defines the incoming tangent
  4970. * @param value2 defines second quaternion
  4971. * @param tangent2 defines the outgoing tangent
  4972. * @param amount defines the target quaternion
  4973. * @returns the new interpolated quaternion
  4974. */
  4975. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4976. var squared = amount * amount;
  4977. var cubed = amount * squared;
  4978. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4979. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4980. var part3 = (cubed - (2.0 * squared)) + amount;
  4981. var part4 = cubed - squared;
  4982. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4983. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4984. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4985. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4986. return new Quaternion(x, y, z, w);
  4987. };
  4988. return Quaternion;
  4989. }());
  4990. BABYLON.Quaternion = Quaternion;
  4991. /**
  4992. * Class used to store matrix data (4x4)
  4993. */
  4994. var Matrix = /** @class */ (function () {
  4995. /**
  4996. * Creates an empty matrix (filled with zeros)
  4997. */
  4998. function Matrix() {
  4999. this._isIdentity = false;
  5000. this._isIdentityDirty = true;
  5001. /**
  5002. * Gets or sets the internal data of the matrix
  5003. */
  5004. this.m = new Float32Array(16);
  5005. this._markAsUpdated();
  5006. }
  5007. /** @hidden */
  5008. Matrix.prototype._markAsUpdated = function () {
  5009. this.updateFlag = Matrix._updateFlagSeed++;
  5010. this._isIdentityDirty = true;
  5011. };
  5012. // Properties
  5013. /**
  5014. * Check if the current matrix is indentity
  5015. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5016. * @returns true is the matrix is the identity matrix
  5017. */
  5018. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5019. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5020. if (this._isIdentityDirty) {
  5021. this._isIdentityDirty = false;
  5022. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5023. this._isIdentity = false;
  5024. }
  5025. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5026. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5027. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5028. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5029. this._isIdentity = false;
  5030. }
  5031. else {
  5032. this._isIdentity = true;
  5033. }
  5034. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5035. this._isIdentity = false;
  5036. }
  5037. }
  5038. return this._isIdentity;
  5039. };
  5040. /**
  5041. * Gets the determinant of the matrix
  5042. * @returns the matrix determinant
  5043. */
  5044. Matrix.prototype.determinant = function () {
  5045. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5046. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5047. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5048. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5049. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5050. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5051. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5052. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5053. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5054. };
  5055. // Methods
  5056. /**
  5057. * Returns the matrix as a Float32Array
  5058. * @returns the matrix underlying array
  5059. */
  5060. Matrix.prototype.toArray = function () {
  5061. return this.m;
  5062. };
  5063. /**
  5064. * Returns the matrix as a Float32Array
  5065. * @returns the matrix underlying array.
  5066. */
  5067. Matrix.prototype.asArray = function () {
  5068. return this.toArray();
  5069. };
  5070. /**
  5071. * Inverts the current matrix in place
  5072. * @returns the current inverted matrix
  5073. */
  5074. Matrix.prototype.invert = function () {
  5075. this.invertToRef(this);
  5076. return this;
  5077. };
  5078. /**
  5079. * Sets all the matrix elements to zero
  5080. * @returns the current matrix
  5081. */
  5082. Matrix.prototype.reset = function () {
  5083. for (var index = 0; index < 16; index++) {
  5084. this.m[index] = 0.0;
  5085. }
  5086. this._markAsUpdated();
  5087. return this;
  5088. };
  5089. /**
  5090. * Adds the current matrix with a second one
  5091. * @param other defines the matrix to add
  5092. * @returns a new matrix as the addition of the current matrix and the given one
  5093. */
  5094. Matrix.prototype.add = function (other) {
  5095. var result = new Matrix();
  5096. this.addToRef(other, result);
  5097. return result;
  5098. };
  5099. /**
  5100. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5101. * @param other defines the matrix to add
  5102. * @param result defines the target matrix
  5103. * @returns the current matrix
  5104. */
  5105. Matrix.prototype.addToRef = function (other, result) {
  5106. for (var index = 0; index < 16; index++) {
  5107. result.m[index] = this.m[index] + other.m[index];
  5108. }
  5109. result._markAsUpdated();
  5110. return this;
  5111. };
  5112. /**
  5113. * Adds in place the given matrix to the current matrix
  5114. * @param other defines the second operand
  5115. * @returns the current updated matrix
  5116. */
  5117. Matrix.prototype.addToSelf = function (other) {
  5118. for (var index = 0; index < 16; index++) {
  5119. this.m[index] += other.m[index];
  5120. }
  5121. this._markAsUpdated();
  5122. return this;
  5123. };
  5124. /**
  5125. * Sets the given matrix to the current inverted Matrix
  5126. * @param other defines the target matrix
  5127. * @returns the unmodified current matrix
  5128. */
  5129. Matrix.prototype.invertToRef = function (other) {
  5130. var l1 = this.m[0];
  5131. var l2 = this.m[1];
  5132. var l3 = this.m[2];
  5133. var l4 = this.m[3];
  5134. var l5 = this.m[4];
  5135. var l6 = this.m[5];
  5136. var l7 = this.m[6];
  5137. var l8 = this.m[7];
  5138. var l9 = this.m[8];
  5139. var l10 = this.m[9];
  5140. var l11 = this.m[10];
  5141. var l12 = this.m[11];
  5142. var l13 = this.m[12];
  5143. var l14 = this.m[13];
  5144. var l15 = this.m[14];
  5145. var l16 = this.m[15];
  5146. var l17 = (l11 * l16) - (l12 * l15);
  5147. var l18 = (l10 * l16) - (l12 * l14);
  5148. var l19 = (l10 * l15) - (l11 * l14);
  5149. var l20 = (l9 * l16) - (l12 * l13);
  5150. var l21 = (l9 * l15) - (l11 * l13);
  5151. var l22 = (l9 * l14) - (l10 * l13);
  5152. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5153. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5154. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5155. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5156. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5157. var l28 = (l7 * l16) - (l8 * l15);
  5158. var l29 = (l6 * l16) - (l8 * l14);
  5159. var l30 = (l6 * l15) - (l7 * l14);
  5160. var l31 = (l5 * l16) - (l8 * l13);
  5161. var l32 = (l5 * l15) - (l7 * l13);
  5162. var l33 = (l5 * l14) - (l6 * l13);
  5163. var l34 = (l7 * l12) - (l8 * l11);
  5164. var l35 = (l6 * l12) - (l8 * l10);
  5165. var l36 = (l6 * l11) - (l7 * l10);
  5166. var l37 = (l5 * l12) - (l8 * l9);
  5167. var l38 = (l5 * l11) - (l7 * l9);
  5168. var l39 = (l5 * l10) - (l6 * l9);
  5169. other.m[0] = l23 * l27;
  5170. other.m[4] = l24 * l27;
  5171. other.m[8] = l25 * l27;
  5172. other.m[12] = l26 * l27;
  5173. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5174. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5175. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5176. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5177. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5178. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5179. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5180. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5181. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5182. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5183. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5184. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5185. other._markAsUpdated();
  5186. return this;
  5187. };
  5188. /**
  5189. * Inserts the translation vector (using 3 floats) in the current matrix
  5190. * @param x defines the 1st component of the translation
  5191. * @param y defines the 2nd component of the translation
  5192. * @param z defines the 3rd component of the translation
  5193. * @returns the current updated matrix
  5194. */
  5195. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5196. this.m[12] = x;
  5197. this.m[13] = y;
  5198. this.m[14] = z;
  5199. this._markAsUpdated();
  5200. return this;
  5201. };
  5202. /**
  5203. * Inserts the translation vector in the current matrix
  5204. * @param vector3 defines the translation to insert
  5205. * @returns the current updated matrix
  5206. */
  5207. Matrix.prototype.setTranslation = function (vector3) {
  5208. this.m[12] = vector3.x;
  5209. this.m[13] = vector3.y;
  5210. this.m[14] = vector3.z;
  5211. this._markAsUpdated();
  5212. return this;
  5213. };
  5214. /**
  5215. * Gets the translation value of the current matrix
  5216. * @returns a new Vector3 as the extracted translation from the matrix
  5217. */
  5218. Matrix.prototype.getTranslation = function () {
  5219. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5220. };
  5221. /**
  5222. * Fill a Vector3 with the extracted translation from the matrix
  5223. * @param result defines the Vector3 where to store the translation
  5224. * @returns the current matrix
  5225. */
  5226. Matrix.prototype.getTranslationToRef = function (result) {
  5227. result.x = this.m[12];
  5228. result.y = this.m[13];
  5229. result.z = this.m[14];
  5230. return this;
  5231. };
  5232. /**
  5233. * Remove rotation and scaling part from the matrix
  5234. * @returns the updated matrix
  5235. */
  5236. Matrix.prototype.removeRotationAndScaling = function () {
  5237. this.setRowFromFloats(0, 1, 0, 0, 0);
  5238. this.setRowFromFloats(1, 0, 1, 0, 0);
  5239. this.setRowFromFloats(2, 0, 0, 1, 0);
  5240. return this;
  5241. };
  5242. /**
  5243. * Multiply two matrices
  5244. * @param other defines the second operand
  5245. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5246. */
  5247. Matrix.prototype.multiply = function (other) {
  5248. var result = new Matrix();
  5249. this.multiplyToRef(other, result);
  5250. return result;
  5251. };
  5252. /**
  5253. * Copy the current matrix from the given one
  5254. * @param other defines the source matrix
  5255. * @returns the current updated matrix
  5256. */
  5257. Matrix.prototype.copyFrom = function (other) {
  5258. for (var index = 0; index < 16; index++) {
  5259. this.m[index] = other.m[index];
  5260. }
  5261. this._markAsUpdated();
  5262. return this;
  5263. };
  5264. /**
  5265. * Populates the given array from the starting index with the current matrix values
  5266. * @param array defines the target array
  5267. * @param offset defines the offset in the target array where to start storing values
  5268. * @returns the current matrix
  5269. */
  5270. Matrix.prototype.copyToArray = function (array, offset) {
  5271. if (offset === void 0) { offset = 0; }
  5272. for (var index = 0; index < 16; index++) {
  5273. array[offset + index] = this.m[index];
  5274. }
  5275. return this;
  5276. };
  5277. /**
  5278. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5279. * @param other defines the second operand
  5280. * @param result defines the matrix where to store the multiplication
  5281. * @returns the current matrix
  5282. */
  5283. Matrix.prototype.multiplyToRef = function (other, result) {
  5284. this.multiplyToArray(other, result.m, 0);
  5285. result._markAsUpdated();
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the array where to store the multiplication
  5292. * @param offset defines the offset in the target array where to start storing values
  5293. * @returns the current matrix
  5294. */
  5295. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5296. var tm0 = this.m[0];
  5297. var tm1 = this.m[1];
  5298. var tm2 = this.m[2];
  5299. var tm3 = this.m[3];
  5300. var tm4 = this.m[4];
  5301. var tm5 = this.m[5];
  5302. var tm6 = this.m[6];
  5303. var tm7 = this.m[7];
  5304. var tm8 = this.m[8];
  5305. var tm9 = this.m[9];
  5306. var tm10 = this.m[10];
  5307. var tm11 = this.m[11];
  5308. var tm12 = this.m[12];
  5309. var tm13 = this.m[13];
  5310. var tm14 = this.m[14];
  5311. var tm15 = this.m[15];
  5312. var om0 = other.m[0];
  5313. var om1 = other.m[1];
  5314. var om2 = other.m[2];
  5315. var om3 = other.m[3];
  5316. var om4 = other.m[4];
  5317. var om5 = other.m[5];
  5318. var om6 = other.m[6];
  5319. var om7 = other.m[7];
  5320. var om8 = other.m[8];
  5321. var om9 = other.m[9];
  5322. var om10 = other.m[10];
  5323. var om11 = other.m[11];
  5324. var om12 = other.m[12];
  5325. var om13 = other.m[13];
  5326. var om14 = other.m[14];
  5327. var om15 = other.m[15];
  5328. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5329. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5330. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5331. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5332. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5333. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5334. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5335. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5336. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5337. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5338. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5339. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5340. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5341. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5342. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5343. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5344. return this;
  5345. };
  5346. /**
  5347. * Check equality between this matrix and a second one
  5348. * @param value defines the second matrix to compare
  5349. * @returns true is the current matrix and the given one values are strictly equal
  5350. */
  5351. Matrix.prototype.equals = function (value) {
  5352. return value &&
  5353. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5354. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5355. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5356. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5357. };
  5358. /**
  5359. * Clone the current matrix
  5360. * @returns a new matrix from the current matrix
  5361. */
  5362. Matrix.prototype.clone = function () {
  5363. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5364. };
  5365. /**
  5366. * Returns the name of the current matrix class
  5367. * @returns the string "Matrix"
  5368. */
  5369. Matrix.prototype.getClassName = function () {
  5370. return "Matrix";
  5371. };
  5372. /**
  5373. * Gets the hash code of the current matrix
  5374. * @returns the hash code
  5375. */
  5376. Matrix.prototype.getHashCode = function () {
  5377. var hash = this.m[0] || 0;
  5378. for (var i = 1; i < 16; i++) {
  5379. hash = (hash * 397) ^ (this.m[i] || 0);
  5380. }
  5381. return hash;
  5382. };
  5383. /**
  5384. * Decomposes the current Matrix into a translation, rotation and scaling components
  5385. * @param scale defines the scale vector3 given as a reference to update
  5386. * @param rotation defines the rotation quaternion given as a reference to update
  5387. * @param translation defines the translation vector3 given as a reference to update
  5388. * @returns true if operation was successful
  5389. */
  5390. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5391. if (translation) {
  5392. translation.x = this.m[12];
  5393. translation.y = this.m[13];
  5394. translation.z = this.m[14];
  5395. }
  5396. scale = scale || MathTmp.Vector3[0];
  5397. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5398. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5399. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5400. if (this.determinant() <= 0) {
  5401. scale.y *= -1;
  5402. }
  5403. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5404. if (rotation) {
  5405. rotation.x = 0;
  5406. rotation.y = 0;
  5407. rotation.z = 0;
  5408. rotation.w = 1;
  5409. }
  5410. return false;
  5411. }
  5412. if (rotation) {
  5413. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5414. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5415. }
  5416. return true;
  5417. };
  5418. /**
  5419. * Gets specific row of the matrix
  5420. * @param index defines the number of the row to get
  5421. * @returns the index-th row of the current matrix as a new Vector4
  5422. */
  5423. Matrix.prototype.getRow = function (index) {
  5424. if (index < 0 || index > 3) {
  5425. return null;
  5426. }
  5427. var i = index * 4;
  5428. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5429. };
  5430. /**
  5431. * Sets the index-th row of the current matrix to the vector4 values
  5432. * @param index defines the number of the row to set
  5433. * @param row defines the target vector4
  5434. * @returns the updated current matrix
  5435. */
  5436. Matrix.prototype.setRow = function (index, row) {
  5437. if (index < 0 || index > 3) {
  5438. return this;
  5439. }
  5440. var i = index * 4;
  5441. this.m[i + 0] = row.x;
  5442. this.m[i + 1] = row.y;
  5443. this.m[i + 2] = row.z;
  5444. this.m[i + 3] = row.w;
  5445. this._markAsUpdated();
  5446. return this;
  5447. };
  5448. /**
  5449. * Compute the transpose of the matrix
  5450. * @returns the new transposed matrix
  5451. */
  5452. Matrix.prototype.transpose = function () {
  5453. return Matrix.Transpose(this);
  5454. };
  5455. /**
  5456. * Compute the transpose of the matrix and store it in a given matrix
  5457. * @param result defines the target matrix
  5458. * @returns the current matrix
  5459. */
  5460. Matrix.prototype.transposeToRef = function (result) {
  5461. Matrix.TransposeToRef(this, result);
  5462. return this;
  5463. };
  5464. /**
  5465. * Sets the index-th row of the current matrix with the given 4 x float values
  5466. * @param index defines the row index
  5467. * @param x defines the x component to set
  5468. * @param y defines the y component to set
  5469. * @param z defines the z component to set
  5470. * @param w defines the w component to set
  5471. * @returns the updated current matrix
  5472. */
  5473. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5474. if (index < 0 || index > 3) {
  5475. return this;
  5476. }
  5477. var i = index * 4;
  5478. this.m[i + 0] = x;
  5479. this.m[i + 1] = y;
  5480. this.m[i + 2] = z;
  5481. this.m[i + 3] = w;
  5482. this._markAsUpdated();
  5483. return this;
  5484. };
  5485. /**
  5486. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5487. * @param scale defines the scale factor
  5488. * @returns a new matrix
  5489. */
  5490. Matrix.prototype.scale = function (scale) {
  5491. var result = new Matrix();
  5492. this.scaleToRef(scale, result);
  5493. return result;
  5494. };
  5495. /**
  5496. * Scale the current matrix values by a factor to a given result matrix
  5497. * @param scale defines the scale factor
  5498. * @param result defines the matrix to store the result
  5499. * @returns the current matrix
  5500. */
  5501. Matrix.prototype.scaleToRef = function (scale, result) {
  5502. for (var index = 0; index < 16; index++) {
  5503. result.m[index] = this.m[index] * scale;
  5504. }
  5505. result._markAsUpdated();
  5506. return this;
  5507. };
  5508. /**
  5509. * Scale the current matrix values by a factor and add the result to a given matrix
  5510. * @param scale defines the scale factor
  5511. * @param result defines the Matrix to store the result
  5512. * @returns the current matrix
  5513. */
  5514. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5515. for (var index = 0; index < 16; index++) {
  5516. result.m[index] += this.m[index] * scale;
  5517. }
  5518. result._markAsUpdated();
  5519. return this;
  5520. };
  5521. /**
  5522. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5523. * @param ref matrix to store the result
  5524. */
  5525. Matrix.prototype.toNormalMatrix = function (ref) {
  5526. this.invertToRef(ref);
  5527. ref.transpose();
  5528. var m = ref.m;
  5529. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5530. };
  5531. /**
  5532. * Gets only rotation part of the current matrix
  5533. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5534. */
  5535. Matrix.prototype.getRotationMatrix = function () {
  5536. var result = Matrix.Identity();
  5537. this.getRotationMatrixToRef(result);
  5538. return result;
  5539. };
  5540. /**
  5541. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5542. * @param result defines the target matrix to store data to
  5543. * @returns the current matrix
  5544. */
  5545. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5546. var m = this.m;
  5547. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5548. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5549. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5550. if (this.determinant() <= 0) {
  5551. sy *= -1;
  5552. }
  5553. if (sx === 0 || sy === 0 || sz === 0) {
  5554. Matrix.IdentityToRef(result);
  5555. }
  5556. else {
  5557. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5558. }
  5559. return this;
  5560. };
  5561. // Statics
  5562. /**
  5563. * Creates a matrix from an array
  5564. * @param array defines the source array
  5565. * @param offset defines an offset in the source array
  5566. * @returns a new Matrix set from the starting index of the given array
  5567. */
  5568. Matrix.FromArray = function (array, offset) {
  5569. var result = new Matrix();
  5570. if (!offset) {
  5571. offset = 0;
  5572. }
  5573. Matrix.FromArrayToRef(array, offset, result);
  5574. return result;
  5575. };
  5576. /**
  5577. * Copy the content of an array into a given matrix
  5578. * @param array defines the source array
  5579. * @param offset defines an offset in the source array
  5580. * @param result defines the target matrix
  5581. */
  5582. Matrix.FromArrayToRef = function (array, offset, result) {
  5583. for (var index = 0; index < 16; index++) {
  5584. result.m[index] = array[index + offset];
  5585. }
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Stores an array into a matrix after having multiplied each component by a given factor
  5590. * @param array defines the source array
  5591. * @param offset defines the offset in the source array
  5592. * @param scale defines the scaling factor
  5593. * @param result defines the target matrix
  5594. */
  5595. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5596. for (var index = 0; index < 16; index++) {
  5597. result.m[index] = array[index + offset] * scale;
  5598. }
  5599. result._markAsUpdated();
  5600. };
  5601. /**
  5602. * Stores a list of values (16) inside a given matrix
  5603. * @param initialM11 defines 1st value of 1st row
  5604. * @param initialM12 defines 2nd value of 1st row
  5605. * @param initialM13 defines 3rd value of 1st row
  5606. * @param initialM14 defines 4th value of 1st row
  5607. * @param initialM21 defines 1st value of 2nd row
  5608. * @param initialM22 defines 2nd value of 2nd row
  5609. * @param initialM23 defines 3rd value of 2nd row
  5610. * @param initialM24 defines 4th value of 2nd row
  5611. * @param initialM31 defines 1st value of 3rd row
  5612. * @param initialM32 defines 2nd value of 3rd row
  5613. * @param initialM33 defines 3rd value of 3rd row
  5614. * @param initialM34 defines 4th value of 3rd row
  5615. * @param initialM41 defines 1st value of 4th row
  5616. * @param initialM42 defines 2nd value of 4th row
  5617. * @param initialM43 defines 3rd value of 4th row
  5618. * @param initialM44 defines 4th value of 4th row
  5619. * @param result defines the target matrix
  5620. */
  5621. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5622. result.m[0] = initialM11;
  5623. result.m[1] = initialM12;
  5624. result.m[2] = initialM13;
  5625. result.m[3] = initialM14;
  5626. result.m[4] = initialM21;
  5627. result.m[5] = initialM22;
  5628. result.m[6] = initialM23;
  5629. result.m[7] = initialM24;
  5630. result.m[8] = initialM31;
  5631. result.m[9] = initialM32;
  5632. result.m[10] = initialM33;
  5633. result.m[11] = initialM34;
  5634. result.m[12] = initialM41;
  5635. result.m[13] = initialM42;
  5636. result.m[14] = initialM43;
  5637. result.m[15] = initialM44;
  5638. result._markAsUpdated();
  5639. };
  5640. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5641. /**
  5642. * Gets an identity matrix that must not be updated
  5643. */
  5644. get: function () {
  5645. return Matrix._identityReadOnly;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. /**
  5651. * Creates new matrix from a list of values (16)
  5652. * @param initialM11 defines 1st value of 1st row
  5653. * @param initialM12 defines 2nd value of 1st row
  5654. * @param initialM13 defines 3rd value of 1st row
  5655. * @param initialM14 defines 4th value of 1st row
  5656. * @param initialM21 defines 1st value of 2nd row
  5657. * @param initialM22 defines 2nd value of 2nd row
  5658. * @param initialM23 defines 3rd value of 2nd row
  5659. * @param initialM24 defines 4th value of 2nd row
  5660. * @param initialM31 defines 1st value of 3rd row
  5661. * @param initialM32 defines 2nd value of 3rd row
  5662. * @param initialM33 defines 3rd value of 3rd row
  5663. * @param initialM34 defines 4th value of 3rd row
  5664. * @param initialM41 defines 1st value of 4th row
  5665. * @param initialM42 defines 2nd value of 4th row
  5666. * @param initialM43 defines 3rd value of 4th row
  5667. * @param initialM44 defines 4th value of 4th row
  5668. * @returns the new matrix
  5669. */
  5670. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5671. var result = new Matrix();
  5672. result.m[0] = initialM11;
  5673. result.m[1] = initialM12;
  5674. result.m[2] = initialM13;
  5675. result.m[3] = initialM14;
  5676. result.m[4] = initialM21;
  5677. result.m[5] = initialM22;
  5678. result.m[6] = initialM23;
  5679. result.m[7] = initialM24;
  5680. result.m[8] = initialM31;
  5681. result.m[9] = initialM32;
  5682. result.m[10] = initialM33;
  5683. result.m[11] = initialM34;
  5684. result.m[12] = initialM41;
  5685. result.m[13] = initialM42;
  5686. result.m[14] = initialM43;
  5687. result.m[15] = initialM44;
  5688. return result;
  5689. };
  5690. /**
  5691. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5692. * @param scale defines the scale vector3
  5693. * @param rotation defines the rotation quaternion
  5694. * @param translation defines the translation vector3
  5695. * @returns a new matrix
  5696. */
  5697. Matrix.Compose = function (scale, rotation, translation) {
  5698. var result = Matrix.Identity();
  5699. Matrix.ComposeToRef(scale, rotation, translation, result);
  5700. return result;
  5701. };
  5702. /**
  5703. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5704. * @param scale defines the scale vector3
  5705. * @param rotation defines the rotation quaternion
  5706. * @param translation defines the translation vector3
  5707. * @param result defines the target matrix
  5708. */
  5709. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5710. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5711. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5712. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5713. result.setTranslation(translation);
  5714. };
  5715. /**
  5716. * Creates a new identity matrix
  5717. * @returns a new identity matrix
  5718. */
  5719. Matrix.Identity = function () {
  5720. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5721. };
  5722. /**
  5723. * Creates a new identity matrix and stores the result in a given matrix
  5724. * @param result defines the target matrix
  5725. */
  5726. Matrix.IdentityToRef = function (result) {
  5727. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5728. };
  5729. /**
  5730. * Creates a new zero matrix
  5731. * @returns a new zero matrix
  5732. */
  5733. Matrix.Zero = function () {
  5734. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5735. };
  5736. /**
  5737. * Creates a new rotation matrix for "angle" radians around the X axis
  5738. * @param angle defines the angle (in radians) to use
  5739. * @return the new matrix
  5740. */
  5741. Matrix.RotationX = function (angle) {
  5742. var result = new Matrix();
  5743. Matrix.RotationXToRef(angle, result);
  5744. return result;
  5745. };
  5746. /**
  5747. * Creates a new matrix as the invert of a given matrix
  5748. * @param source defines the source matrix
  5749. * @returns the new matrix
  5750. */
  5751. Matrix.Invert = function (source) {
  5752. var result = new Matrix();
  5753. source.invertToRef(result);
  5754. return result;
  5755. };
  5756. /**
  5757. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5758. * @param angle defines the angle (in radians) to use
  5759. * @param result defines the target matrix
  5760. */
  5761. Matrix.RotationXToRef = function (angle, result) {
  5762. var s = Math.sin(angle);
  5763. var c = Math.cos(angle);
  5764. result.m[0] = 1.0;
  5765. result.m[15] = 1.0;
  5766. result.m[5] = c;
  5767. result.m[10] = c;
  5768. result.m[9] = -s;
  5769. result.m[6] = s;
  5770. result.m[1] = 0.0;
  5771. result.m[2] = 0.0;
  5772. result.m[3] = 0.0;
  5773. result.m[4] = 0.0;
  5774. result.m[7] = 0.0;
  5775. result.m[8] = 0.0;
  5776. result.m[11] = 0.0;
  5777. result.m[12] = 0.0;
  5778. result.m[13] = 0.0;
  5779. result.m[14] = 0.0;
  5780. result._markAsUpdated();
  5781. };
  5782. /**
  5783. * Creates a new rotation matrix for "angle" radians around the Y axis
  5784. * @param angle defines the angle (in radians) to use
  5785. * @return the new matrix
  5786. */
  5787. Matrix.RotationY = function (angle) {
  5788. var result = new Matrix();
  5789. Matrix.RotationYToRef(angle, result);
  5790. return result;
  5791. };
  5792. /**
  5793. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5794. * @param angle defines the angle (in radians) to use
  5795. * @param result defines the target matrix
  5796. */
  5797. Matrix.RotationYToRef = function (angle, result) {
  5798. var s = Math.sin(angle);
  5799. var c = Math.cos(angle);
  5800. result.m[5] = 1.0;
  5801. result.m[15] = 1.0;
  5802. result.m[0] = c;
  5803. result.m[2] = -s;
  5804. result.m[8] = s;
  5805. result.m[10] = c;
  5806. result.m[1] = 0.0;
  5807. result.m[3] = 0.0;
  5808. result.m[4] = 0.0;
  5809. result.m[6] = 0.0;
  5810. result.m[7] = 0.0;
  5811. result.m[9] = 0.0;
  5812. result.m[11] = 0.0;
  5813. result.m[12] = 0.0;
  5814. result.m[13] = 0.0;
  5815. result.m[14] = 0.0;
  5816. result._markAsUpdated();
  5817. };
  5818. /**
  5819. * Creates a new rotation matrix for "angle" radians around the Z axis
  5820. * @param angle defines the angle (in radians) to use
  5821. * @return the new matrix
  5822. */
  5823. Matrix.RotationZ = function (angle) {
  5824. var result = new Matrix();
  5825. Matrix.RotationZToRef(angle, result);
  5826. return result;
  5827. };
  5828. /**
  5829. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5830. * @param angle defines the angle (in radians) to use
  5831. * @param result defines the target matrix
  5832. */
  5833. Matrix.RotationZToRef = function (angle, result) {
  5834. var s = Math.sin(angle);
  5835. var c = Math.cos(angle);
  5836. result.m[10] = 1.0;
  5837. result.m[15] = 1.0;
  5838. result.m[0] = c;
  5839. result.m[1] = s;
  5840. result.m[4] = -s;
  5841. result.m[5] = c;
  5842. result.m[2] = 0.0;
  5843. result.m[3] = 0.0;
  5844. result.m[6] = 0.0;
  5845. result.m[7] = 0.0;
  5846. result.m[8] = 0.0;
  5847. result.m[9] = 0.0;
  5848. result.m[11] = 0.0;
  5849. result.m[12] = 0.0;
  5850. result.m[13] = 0.0;
  5851. result.m[14] = 0.0;
  5852. result._markAsUpdated();
  5853. };
  5854. /**
  5855. * Creates a new rotation matrix for "angle" radians around the given axis
  5856. * @param axis defines the axis to use
  5857. * @param angle defines the angle (in radians) to use
  5858. * @return the new matrix
  5859. */
  5860. Matrix.RotationAxis = function (axis, angle) {
  5861. var result = Matrix.Zero();
  5862. Matrix.RotationAxisToRef(axis, angle, result);
  5863. return result;
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @param result defines the target matrix
  5870. */
  5871. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5872. var s = Math.sin(-angle);
  5873. var c = Math.cos(-angle);
  5874. var c1 = 1 - c;
  5875. axis.normalize();
  5876. result.m[0] = (axis.x * axis.x) * c1 + c;
  5877. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5878. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5879. result.m[3] = 0.0;
  5880. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5881. result.m[5] = (axis.y * axis.y) * c1 + c;
  5882. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5883. result.m[7] = 0.0;
  5884. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5885. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5886. result.m[10] = (axis.z * axis.z) * c1 + c;
  5887. result.m[11] = 0.0;
  5888. result.m[15] = 1.0;
  5889. result._markAsUpdated();
  5890. };
  5891. /**
  5892. * Creates a rotation matrix
  5893. * @param yaw defines the yaw angle in radians (Y axis)
  5894. * @param pitch defines the pitch angle in radians (X axis)
  5895. * @param roll defines the roll angle in radians (X axis)
  5896. * @returns the new rotation matrix
  5897. */
  5898. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5899. var result = new Matrix();
  5900. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5901. return result;
  5902. };
  5903. /**
  5904. * Creates a rotation matrix and stores it in a given matrix
  5905. * @param yaw defines the yaw angle in radians (Y axis)
  5906. * @param pitch defines the pitch angle in radians (X axis)
  5907. * @param roll defines the roll angle in radians (X axis)
  5908. * @param result defines the target matrix
  5909. */
  5910. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5911. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5912. this._tempQuaternion.toRotationMatrix(result);
  5913. };
  5914. /**
  5915. * Creates a scaling matrix
  5916. * @param x defines the scale factor on X axis
  5917. * @param y defines the scale factor on Y axis
  5918. * @param z defines the scale factor on Z axis
  5919. * @returns the new matrix
  5920. */
  5921. Matrix.Scaling = function (x, y, z) {
  5922. var result = Matrix.Zero();
  5923. Matrix.ScalingToRef(x, y, z, result);
  5924. return result;
  5925. };
  5926. /**
  5927. * Creates a scaling matrix and stores it in a given matrix
  5928. * @param x defines the scale factor on X axis
  5929. * @param y defines the scale factor on Y axis
  5930. * @param z defines the scale factor on Z axis
  5931. * @param result defines the target matrix
  5932. */
  5933. Matrix.ScalingToRef = function (x, y, z, result) {
  5934. result.m[0] = x;
  5935. result.m[1] = 0.0;
  5936. result.m[2] = 0.0;
  5937. result.m[3] = 0.0;
  5938. result.m[4] = 0.0;
  5939. result.m[5] = y;
  5940. result.m[6] = 0.0;
  5941. result.m[7] = 0.0;
  5942. result.m[8] = 0.0;
  5943. result.m[9] = 0.0;
  5944. result.m[10] = z;
  5945. result.m[11] = 0.0;
  5946. result.m[12] = 0.0;
  5947. result.m[13] = 0.0;
  5948. result.m[14] = 0.0;
  5949. result.m[15] = 1.0;
  5950. result._markAsUpdated();
  5951. };
  5952. /**
  5953. * Creates a translation matrix
  5954. * @param x defines the translation on X axis
  5955. * @param y defines the translation on Y axis
  5956. * @param z defines the translationon Z axis
  5957. * @returns the new matrix
  5958. */
  5959. Matrix.Translation = function (x, y, z) {
  5960. var result = Matrix.Identity();
  5961. Matrix.TranslationToRef(x, y, z, result);
  5962. return result;
  5963. };
  5964. /**
  5965. * Creates a translation matrix and stores it in a given matrix
  5966. * @param x defines the translation on X axis
  5967. * @param y defines the translation on Y axis
  5968. * @param z defines the translationon Z axis
  5969. * @param result defines the target matrix
  5970. */
  5971. Matrix.TranslationToRef = function (x, y, z, result) {
  5972. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5973. };
  5974. /**
  5975. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5976. * @param startValue defines the start value
  5977. * @param endValue defines the end value
  5978. * @param gradient defines the gradient factor
  5979. * @returns the new matrix
  5980. */
  5981. Matrix.Lerp = function (startValue, endValue, gradient) {
  5982. var result = Matrix.Zero();
  5983. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5984. return result;
  5985. };
  5986. /**
  5987. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5988. * @param startValue defines the start value
  5989. * @param endValue defines the end value
  5990. * @param gradient defines the gradient factor
  5991. * @param result defines the Matrix object where to store data
  5992. */
  5993. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5994. for (var index = 0; index < 16; index++) {
  5995. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5996. }
  5997. result._markAsUpdated();
  5998. };
  5999. /**
  6000. * Builds a new matrix whose values are computed by:
  6001. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6002. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6003. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6004. * @param startValue defines the first matrix
  6005. * @param endValue defines the second matrix
  6006. * @param gradient defines the gradient between the two matrices
  6007. * @returns the new matrix
  6008. */
  6009. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6010. var result = Matrix.Zero();
  6011. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6012. return result;
  6013. };
  6014. /**
  6015. * Update a matrix to values which are computed by:
  6016. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6017. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6018. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6019. * @param startValue defines the first matrix
  6020. * @param endValue defines the second matrix
  6021. * @param gradient defines the gradient between the two matrices
  6022. * @param result defines the target matrix
  6023. */
  6024. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6025. var startScale = MathTmp.Vector3[0];
  6026. var startRotation = MathTmp.Quaternion[0];
  6027. var startTranslation = MathTmp.Vector3[1];
  6028. startValue.decompose(startScale, startRotation, startTranslation);
  6029. var endScale = MathTmp.Vector3[2];
  6030. var endRotation = MathTmp.Quaternion[1];
  6031. var endTranslation = MathTmp.Vector3[3];
  6032. endValue.decompose(endScale, endRotation, endTranslation);
  6033. var resultScale = MathTmp.Vector3[4];
  6034. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6035. var resultRotation = MathTmp.Quaternion[2];
  6036. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6037. var resultTranslation = MathTmp.Vector3[5];
  6038. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6039. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6040. };
  6041. /**
  6042. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6043. * This function works in left handed mode
  6044. * @param eye defines the final position of the entity
  6045. * @param target defines where the entity should look at
  6046. * @param up defines the up vector for the entity
  6047. * @returns the new matrix
  6048. */
  6049. Matrix.LookAtLH = function (eye, target, up) {
  6050. var result = Matrix.Zero();
  6051. Matrix.LookAtLHToRef(eye, target, up, result);
  6052. return result;
  6053. };
  6054. /**
  6055. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6056. * This function works in left handed mode
  6057. * @param eye defines the final position of the entity
  6058. * @param target defines where the entity should look at
  6059. * @param up defines the up vector for the entity
  6060. * @param result defines the target matrix
  6061. */
  6062. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6063. // Z axis
  6064. target.subtractToRef(eye, this._zAxis);
  6065. this._zAxis.normalize();
  6066. // X axis
  6067. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6068. if (this._xAxis.lengthSquared() === 0) {
  6069. this._xAxis.x = 1.0;
  6070. }
  6071. else {
  6072. this._xAxis.normalize();
  6073. }
  6074. // Y axis
  6075. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6076. this._yAxis.normalize();
  6077. // Eye angles
  6078. var ex = -Vector3.Dot(this._xAxis, eye);
  6079. var ey = -Vector3.Dot(this._yAxis, eye);
  6080. var ez = -Vector3.Dot(this._zAxis, eye);
  6081. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6082. };
  6083. /**
  6084. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6085. * This function works in right handed mode
  6086. * @param eye defines the final position of the entity
  6087. * @param target defines where the entity should look at
  6088. * @param up defines the up vector for the entity
  6089. * @returns the new matrix
  6090. */
  6091. Matrix.LookAtRH = function (eye, target, up) {
  6092. var result = Matrix.Zero();
  6093. Matrix.LookAtRHToRef(eye, target, up, result);
  6094. return result;
  6095. };
  6096. /**
  6097. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6098. * This function works in right handed mode
  6099. * @param eye defines the final position of the entity
  6100. * @param target defines where the entity should look at
  6101. * @param up defines the up vector for the entity
  6102. * @param result defines the target matrix
  6103. */
  6104. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6105. // Z axis
  6106. eye.subtractToRef(target, this._zAxis);
  6107. this._zAxis.normalize();
  6108. // X axis
  6109. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6110. if (this._xAxis.lengthSquared() === 0) {
  6111. this._xAxis.x = 1.0;
  6112. }
  6113. else {
  6114. this._xAxis.normalize();
  6115. }
  6116. // Y axis
  6117. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6118. this._yAxis.normalize();
  6119. // Eye angles
  6120. var ex = -Vector3.Dot(this._xAxis, eye);
  6121. var ey = -Vector3.Dot(this._yAxis, eye);
  6122. var ez = -Vector3.Dot(this._zAxis, eye);
  6123. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6124. };
  6125. /**
  6126. * Create a left-handed orthographic projection matrix
  6127. * @param width defines the viewport width
  6128. * @param height defines the viewport height
  6129. * @param znear defines the near clip plane
  6130. * @param zfar defines the far clip plane
  6131. * @returns a new matrix as a left-handed orthographic projection matrix
  6132. */
  6133. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6134. var matrix = Matrix.Zero();
  6135. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6136. return matrix;
  6137. };
  6138. /**
  6139. * Store a left-handed orthographic projection to a given matrix
  6140. * @param width defines the viewport width
  6141. * @param height defines the viewport height
  6142. * @param znear defines the near clip plane
  6143. * @param zfar defines the far clip plane
  6144. * @param result defines the target matrix
  6145. */
  6146. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6147. var n = znear;
  6148. var f = zfar;
  6149. var a = 2.0 / width;
  6150. var b = 2.0 / height;
  6151. var c = 2.0 / (f - n);
  6152. var d = -(f + n) / (f - n);
  6153. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6154. };
  6155. /**
  6156. * Create a left-handed orthographic projection matrix
  6157. * @param left defines the viewport left coordinate
  6158. * @param right defines the viewport right coordinate
  6159. * @param bottom defines the viewport bottom coordinate
  6160. * @param top defines the viewport top coordinate
  6161. * @param znear defines the near clip plane
  6162. * @param zfar defines the far clip plane
  6163. * @returns a new matrix as a left-handed orthographic projection matrix
  6164. */
  6165. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6166. var matrix = Matrix.Zero();
  6167. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6168. return matrix;
  6169. };
  6170. /**
  6171. * Stores a left-handed orthographic projection into a given matrix
  6172. * @param left defines the viewport left coordinate
  6173. * @param right defines the viewport right coordinate
  6174. * @param bottom defines the viewport bottom coordinate
  6175. * @param top defines the viewport top coordinate
  6176. * @param znear defines the near clip plane
  6177. * @param zfar defines the far clip plane
  6178. * @param result defines the target matrix
  6179. */
  6180. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6181. var n = znear;
  6182. var f = zfar;
  6183. var a = 2.0 / (right - left);
  6184. var b = 2.0 / (top - bottom);
  6185. var c = 2.0 / (f - n);
  6186. var d = -(f + n) / (f - n);
  6187. var i0 = (left + right) / (left - right);
  6188. var i1 = (top + bottom) / (bottom - top);
  6189. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6190. };
  6191. /**
  6192. * Creates a right-handed orthographic projection matrix
  6193. * @param left defines the viewport left coordinate
  6194. * @param right defines the viewport right coordinate
  6195. * @param bottom defines the viewport bottom coordinate
  6196. * @param top defines the viewport top coordinate
  6197. * @param znear defines the near clip plane
  6198. * @param zfar defines the far clip plane
  6199. * @returns a new matrix as a right-handed orthographic projection matrix
  6200. */
  6201. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6202. var matrix = Matrix.Zero();
  6203. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6204. return matrix;
  6205. };
  6206. /**
  6207. * Stores a right-handed orthographic projection into a given matrix
  6208. * @param left defines the viewport left coordinate
  6209. * @param right defines the viewport right coordinate
  6210. * @param bottom defines the viewport bottom coordinate
  6211. * @param top defines the viewport top coordinate
  6212. * @param znear defines the near clip plane
  6213. * @param zfar defines the far clip plane
  6214. * @param result defines the target matrix
  6215. */
  6216. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6217. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6218. result.m[10] *= -1.0;
  6219. };
  6220. /**
  6221. * Creates a left-handed perspective projection matrix
  6222. * @param width defines the viewport width
  6223. * @param height defines the viewport height
  6224. * @param znear defines the near clip plane
  6225. * @param zfar defines the far clip plane
  6226. * @returns a new matrix as a left-handed perspective projection matrix
  6227. */
  6228. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6229. var matrix = Matrix.Zero();
  6230. var n = znear;
  6231. var f = zfar;
  6232. var a = 2.0 * n / width;
  6233. var b = 2.0 * n / height;
  6234. var c = (f + n) / (f - n);
  6235. var d = -2.0 * f * n / (f - n);
  6236. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6237. return matrix;
  6238. };
  6239. /**
  6240. * Creates a left-handed perspective projection matrix
  6241. * @param fov defines the horizontal field of view
  6242. * @param aspect defines the aspect ratio
  6243. * @param znear defines the near clip plane
  6244. * @param zfar defines the far clip plane
  6245. * @returns a new matrix as a left-handed perspective projection matrix
  6246. */
  6247. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6248. var matrix = Matrix.Zero();
  6249. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6250. return matrix;
  6251. };
  6252. /**
  6253. * Stores a left-handed perspective projection into a given matrix
  6254. * @param fov defines the horizontal field of view
  6255. * @param aspect defines the aspect ratio
  6256. * @param znear defines the near clip plane
  6257. * @param zfar defines the far clip plane
  6258. * @param result defines the target matrix
  6259. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6260. */
  6261. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6262. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6263. var n = znear;
  6264. var f = zfar;
  6265. var t = 1.0 / (Math.tan(fov * 0.5));
  6266. var a = isVerticalFovFixed ? (t / aspect) : t;
  6267. var b = isVerticalFovFixed ? t : (t * aspect);
  6268. var c = (f + n) / (f - n);
  6269. var d = -2.0 * f * n / (f - n);
  6270. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6271. };
  6272. /**
  6273. * Creates a right-handed perspective projection matrix
  6274. * @param fov defines the horizontal field of view
  6275. * @param aspect defines the aspect ratio
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @returns a new matrix as a right-handed perspective projection matrix
  6279. */
  6280. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6281. var matrix = Matrix.Zero();
  6282. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6283. return matrix;
  6284. };
  6285. /**
  6286. * Stores a right-handed perspective projection into a given matrix
  6287. * @param fov defines the horizontal field of view
  6288. * @param aspect defines the aspect ratio
  6289. * @param znear defines the near clip plane
  6290. * @param zfar defines the far clip plane
  6291. * @param result defines the target matrix
  6292. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6293. */
  6294. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6295. //alternatively this could be expressed as:
  6296. // m = PerspectiveFovLHToRef
  6297. // m[10] *= -1.0;
  6298. // m[11] *= -1.0;
  6299. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6300. var n = znear;
  6301. var f = zfar;
  6302. var t = 1.0 / (Math.tan(fov * 0.5));
  6303. var a = isVerticalFovFixed ? (t / aspect) : t;
  6304. var b = isVerticalFovFixed ? t : (t * aspect);
  6305. var c = -(f + n) / (f - n);
  6306. var d = -2 * f * n / (f - n);
  6307. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6308. };
  6309. /**
  6310. * Stores a perspective projection for WebVR info a given matrix
  6311. * @param fov defines the field of view
  6312. * @param znear defines the near clip plane
  6313. * @param zfar defines the far clip plane
  6314. * @param result defines the target matrix
  6315. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6316. */
  6317. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6318. if (rightHanded === void 0) { rightHanded = false; }
  6319. var rightHandedFactor = rightHanded ? -1 : 1;
  6320. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6321. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6322. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6323. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6324. var xScale = 2.0 / (leftTan + rightTan);
  6325. var yScale = 2.0 / (upTan + downTan);
  6326. result.m[0] = xScale;
  6327. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6328. result.m[5] = yScale;
  6329. result.m[6] = result.m[7] = 0.0;
  6330. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6331. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6332. result.m[10] = -zfar / (znear - zfar);
  6333. result.m[11] = 1.0 * rightHandedFactor;
  6334. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6335. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6336. result._markAsUpdated();
  6337. };
  6338. /**
  6339. * Computes a complete transformation matrix
  6340. * @param viewport defines the viewport to use
  6341. * @param world defines the world matrix
  6342. * @param view defines the view matrix
  6343. * @param projection defines the projection matrix
  6344. * @param zmin defines the near clip plane
  6345. * @param zmax defines the far clip plane
  6346. * @returns the transformation matrix
  6347. */
  6348. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6349. var cw = viewport.width;
  6350. var ch = viewport.height;
  6351. var cx = viewport.x;
  6352. var cy = viewport.y;
  6353. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6354. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6355. };
  6356. /**
  6357. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6358. * @param matrix defines the matrix to use
  6359. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6360. */
  6361. Matrix.GetAsMatrix2x2 = function (matrix) {
  6362. return new Float32Array([
  6363. matrix.m[0], matrix.m[1],
  6364. matrix.m[4], matrix.m[5]
  6365. ]);
  6366. };
  6367. /**
  6368. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix3x3 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1], matrix.m[2],
  6375. matrix.m[4], matrix.m[5], matrix.m[6],
  6376. matrix.m[8], matrix.m[9], matrix.m[10]
  6377. ]);
  6378. };
  6379. /**
  6380. * Compute the transpose of a given matrix
  6381. * @param matrix defines the matrix to transpose
  6382. * @returns the new matrix
  6383. */
  6384. Matrix.Transpose = function (matrix) {
  6385. var result = new Matrix();
  6386. Matrix.TransposeToRef(matrix, result);
  6387. return result;
  6388. };
  6389. /**
  6390. * Compute the transpose of a matrix and store it in a target matrix
  6391. * @param matrix defines the matrix to transpose
  6392. * @param result defines the target matrix
  6393. */
  6394. Matrix.TransposeToRef = function (matrix, result) {
  6395. result.m[0] = matrix.m[0];
  6396. result.m[1] = matrix.m[4];
  6397. result.m[2] = matrix.m[8];
  6398. result.m[3] = matrix.m[12];
  6399. result.m[4] = matrix.m[1];
  6400. result.m[5] = matrix.m[5];
  6401. result.m[6] = matrix.m[9];
  6402. result.m[7] = matrix.m[13];
  6403. result.m[8] = matrix.m[2];
  6404. result.m[9] = matrix.m[6];
  6405. result.m[10] = matrix.m[10];
  6406. result.m[11] = matrix.m[14];
  6407. result.m[12] = matrix.m[3];
  6408. result.m[13] = matrix.m[7];
  6409. result.m[14] = matrix.m[11];
  6410. result.m[15] = matrix.m[15];
  6411. };
  6412. /**
  6413. * Computes a reflection matrix from a plane
  6414. * @param plane defines the reflection plane
  6415. * @returns a new matrix
  6416. */
  6417. Matrix.Reflection = function (plane) {
  6418. var matrix = new Matrix();
  6419. Matrix.ReflectionToRef(plane, matrix);
  6420. return matrix;
  6421. };
  6422. /**
  6423. * Computes a reflection matrix from a plane
  6424. * @param plane defines the reflection plane
  6425. * @param result defines the target matrix
  6426. */
  6427. Matrix.ReflectionToRef = function (plane, result) {
  6428. plane.normalize();
  6429. var x = plane.normal.x;
  6430. var y = plane.normal.y;
  6431. var z = plane.normal.z;
  6432. var temp = -2 * x;
  6433. var temp2 = -2 * y;
  6434. var temp3 = -2 * z;
  6435. result.m[0] = (temp * x) + 1;
  6436. result.m[1] = temp2 * x;
  6437. result.m[2] = temp3 * x;
  6438. result.m[3] = 0.0;
  6439. result.m[4] = temp * y;
  6440. result.m[5] = (temp2 * y) + 1;
  6441. result.m[6] = temp3 * y;
  6442. result.m[7] = 0.0;
  6443. result.m[8] = temp * z;
  6444. result.m[9] = temp2 * z;
  6445. result.m[10] = (temp3 * z) + 1;
  6446. result.m[11] = 0.0;
  6447. result.m[12] = temp * plane.d;
  6448. result.m[13] = temp2 * plane.d;
  6449. result.m[14] = temp3 * plane.d;
  6450. result.m[15] = 1.0;
  6451. result._markAsUpdated();
  6452. };
  6453. /**
  6454. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6455. * @param xaxis defines the value of the 1st axis
  6456. * @param yaxis defines the value of the 2nd axis
  6457. * @param zaxis defines the value of the 3rd axis
  6458. * @param result defines the target matrix
  6459. */
  6460. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6461. result.m[0] = xaxis.x;
  6462. result.m[1] = xaxis.y;
  6463. result.m[2] = xaxis.z;
  6464. result.m[3] = 0.0;
  6465. result.m[4] = yaxis.x;
  6466. result.m[5] = yaxis.y;
  6467. result.m[6] = yaxis.z;
  6468. result.m[7] = 0.0;
  6469. result.m[8] = zaxis.x;
  6470. result.m[9] = zaxis.y;
  6471. result.m[10] = zaxis.z;
  6472. result.m[11] = 0.0;
  6473. result.m[12] = 0.0;
  6474. result.m[13] = 0.0;
  6475. result.m[14] = 0.0;
  6476. result.m[15] = 1.0;
  6477. result._markAsUpdated();
  6478. };
  6479. /**
  6480. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6481. * @param quat defines the quaternion to use
  6482. * @param result defines the target matrix
  6483. */
  6484. Matrix.FromQuaternionToRef = function (quat, result) {
  6485. var xx = quat.x * quat.x;
  6486. var yy = quat.y * quat.y;
  6487. var zz = quat.z * quat.z;
  6488. var xy = quat.x * quat.y;
  6489. var zw = quat.z * quat.w;
  6490. var zx = quat.z * quat.x;
  6491. var yw = quat.y * quat.w;
  6492. var yz = quat.y * quat.z;
  6493. var xw = quat.x * quat.w;
  6494. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6495. result.m[1] = 2.0 * (xy + zw);
  6496. result.m[2] = 2.0 * (zx - yw);
  6497. result.m[3] = 0.0;
  6498. result.m[4] = 2.0 * (xy - zw);
  6499. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6500. result.m[6] = 2.0 * (yz + xw);
  6501. result.m[7] = 0.0;
  6502. result.m[8] = 2.0 * (zx + yw);
  6503. result.m[9] = 2.0 * (yz - xw);
  6504. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6505. result.m[11] = 0.0;
  6506. result.m[12] = 0.0;
  6507. result.m[13] = 0.0;
  6508. result.m[14] = 0.0;
  6509. result.m[15] = 1.0;
  6510. result._markAsUpdated();
  6511. };
  6512. Matrix._tempQuaternion = new Quaternion();
  6513. Matrix._xAxis = Vector3.Zero();
  6514. Matrix._yAxis = Vector3.Zero();
  6515. Matrix._zAxis = Vector3.Zero();
  6516. Matrix._updateFlagSeed = 0;
  6517. Matrix._identityReadOnly = Matrix.Identity();
  6518. return Matrix;
  6519. }());
  6520. BABYLON.Matrix = Matrix;
  6521. var Plane = /** @class */ (function () {
  6522. /**
  6523. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6524. */
  6525. function Plane(a, b, c, d) {
  6526. this.normal = new Vector3(a, b, c);
  6527. this.d = d;
  6528. }
  6529. /**
  6530. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6531. */
  6532. Plane.prototype.asArray = function () {
  6533. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6534. };
  6535. // Methods
  6536. /**
  6537. * Returns a new plane copied from the current Plane.
  6538. */
  6539. Plane.prototype.clone = function () {
  6540. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6541. };
  6542. /**
  6543. * Returns the string "Plane".
  6544. */
  6545. Plane.prototype.getClassName = function () {
  6546. return "Plane";
  6547. };
  6548. /**
  6549. * Returns the Plane hash code.
  6550. */
  6551. Plane.prototype.getHashCode = function () {
  6552. var hash = this.normal.getHashCode();
  6553. hash = (hash * 397) ^ (this.d || 0);
  6554. return hash;
  6555. };
  6556. /**
  6557. * Normalize the current Plane in place.
  6558. * Returns the updated Plane.
  6559. */
  6560. Plane.prototype.normalize = function () {
  6561. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6562. var magnitude = 0.0;
  6563. if (norm !== 0) {
  6564. magnitude = 1.0 / norm;
  6565. }
  6566. this.normal.x *= magnitude;
  6567. this.normal.y *= magnitude;
  6568. this.normal.z *= magnitude;
  6569. this.d *= magnitude;
  6570. return this;
  6571. };
  6572. /**
  6573. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6574. */
  6575. Plane.prototype.transform = function (transformation) {
  6576. var transposedMatrix = Matrix.Transpose(transformation);
  6577. var x = this.normal.x;
  6578. var y = this.normal.y;
  6579. var z = this.normal.z;
  6580. var d = this.d;
  6581. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6582. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6583. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6584. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6585. return new Plane(normalX, normalY, normalZ, finalD);
  6586. };
  6587. /**
  6588. * Returns the dot product (float) of the point coordinates and the plane normal.
  6589. */
  6590. Plane.prototype.dotCoordinate = function (point) {
  6591. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6592. };
  6593. /**
  6594. * Updates the current Plane from the plane defined by the three given points.
  6595. * Returns the updated Plane.
  6596. */
  6597. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6598. var x1 = point2.x - point1.x;
  6599. var y1 = point2.y - point1.y;
  6600. var z1 = point2.z - point1.z;
  6601. var x2 = point3.x - point1.x;
  6602. var y2 = point3.y - point1.y;
  6603. var z2 = point3.z - point1.z;
  6604. var yz = (y1 * z2) - (z1 * y2);
  6605. var xz = (z1 * x2) - (x1 * z2);
  6606. var xy = (x1 * y2) - (y1 * x2);
  6607. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6608. var invPyth;
  6609. if (pyth !== 0) {
  6610. invPyth = 1.0 / pyth;
  6611. }
  6612. else {
  6613. invPyth = 0.0;
  6614. }
  6615. this.normal.x = yz * invPyth;
  6616. this.normal.y = xz * invPyth;
  6617. this.normal.z = xy * invPyth;
  6618. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6619. return this;
  6620. };
  6621. /**
  6622. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6623. */
  6624. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6625. var dot = Vector3.Dot(this.normal, direction);
  6626. return (dot <= epsilon);
  6627. };
  6628. /**
  6629. * Returns the signed distance (float) from the given point to the Plane.
  6630. */
  6631. Plane.prototype.signedDistanceTo = function (point) {
  6632. return Vector3.Dot(point, this.normal) + this.d;
  6633. };
  6634. // Statics
  6635. /**
  6636. * Returns a new Plane from the given array.
  6637. */
  6638. Plane.FromArray = function (array) {
  6639. return new Plane(array[0], array[1], array[2], array[3]);
  6640. };
  6641. /**
  6642. * Returns a new Plane defined by the three given points.
  6643. */
  6644. Plane.FromPoints = function (point1, point2, point3) {
  6645. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6646. result.copyFromPoints(point1, point2, point3);
  6647. return result;
  6648. };
  6649. /**
  6650. * Returns a new Plane the normal vector to this plane at the given origin point.
  6651. * Note : the vector "normal" is updated because normalized.
  6652. */
  6653. Plane.FromPositionAndNormal = function (origin, normal) {
  6654. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6655. normal.normalize();
  6656. result.normal = normal;
  6657. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6662. */
  6663. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6664. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6665. return Vector3.Dot(point, normal) + d;
  6666. };
  6667. return Plane;
  6668. }());
  6669. BABYLON.Plane = Plane;
  6670. var Viewport = /** @class */ (function () {
  6671. /**
  6672. * Creates a Viewport object located at (x, y) and sized (width, height).
  6673. */
  6674. function Viewport(x, y, width, height) {
  6675. this.x = x;
  6676. this.y = y;
  6677. this.width = width;
  6678. this.height = height;
  6679. }
  6680. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6681. if (renderWidthOrEngine.getRenderWidth) {
  6682. var engine = renderWidthOrEngine;
  6683. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6684. }
  6685. var renderWidth = renderWidthOrEngine;
  6686. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6687. };
  6688. /**
  6689. * Returns a new Viewport copied from the current one.
  6690. */
  6691. Viewport.prototype.clone = function () {
  6692. return new Viewport(this.x, this.y, this.width, this.height);
  6693. };
  6694. return Viewport;
  6695. }());
  6696. BABYLON.Viewport = Viewport;
  6697. var Frustum = /** @class */ (function () {
  6698. function Frustum() {
  6699. }
  6700. /**
  6701. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6702. */
  6703. Frustum.GetPlanes = function (transform) {
  6704. var frustumPlanes = [];
  6705. for (var index = 0; index < 6; index++) {
  6706. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6707. }
  6708. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6709. return frustumPlanes;
  6710. };
  6711. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6712. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6713. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6714. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6715. frustumPlane.d = transform.m[15] + transform.m[14];
  6716. frustumPlane.normalize();
  6717. };
  6718. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6719. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6720. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6721. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6722. frustumPlane.d = transform.m[15] - transform.m[14];
  6723. frustumPlane.normalize();
  6724. };
  6725. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6726. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6727. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6728. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6729. frustumPlane.d = transform.m[15] + transform.m[12];
  6730. frustumPlane.normalize();
  6731. };
  6732. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6733. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6734. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6735. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6736. frustumPlane.d = transform.m[15] - transform.m[12];
  6737. frustumPlane.normalize();
  6738. };
  6739. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6740. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6741. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6742. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6743. frustumPlane.d = transform.m[15] - transform.m[13];
  6744. frustumPlane.normalize();
  6745. };
  6746. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6747. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6748. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6749. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6750. frustumPlane.d = transform.m[15] + transform.m[13];
  6751. frustumPlane.normalize();
  6752. };
  6753. /**
  6754. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6755. */
  6756. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6757. // Near
  6758. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6759. // Far
  6760. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6761. // Left
  6762. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6763. // Right
  6764. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6765. // Top
  6766. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6767. // Bottom
  6768. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6769. };
  6770. return Frustum;
  6771. }());
  6772. BABYLON.Frustum = Frustum;
  6773. /** Defines supported spaces */
  6774. var Space;
  6775. (function (Space) {
  6776. /** Local (object) space */
  6777. Space[Space["LOCAL"] = 0] = "LOCAL";
  6778. /** World space */
  6779. Space[Space["WORLD"] = 1] = "WORLD";
  6780. /** Bone space */
  6781. Space[Space["BONE"] = 2] = "BONE";
  6782. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6783. /** Defines the 3 main axes */
  6784. var Axis = /** @class */ (function () {
  6785. function Axis() {
  6786. }
  6787. /** X axis */
  6788. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6789. /** Y axis */
  6790. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6791. /** Z axis */
  6792. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6793. return Axis;
  6794. }());
  6795. BABYLON.Axis = Axis;
  6796. ;
  6797. var BezierCurve = /** @class */ (function () {
  6798. function BezierCurve() {
  6799. }
  6800. /**
  6801. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6802. */
  6803. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6804. // Extract X (which is equal to time here)
  6805. var f0 = 1 - 3 * x2 + 3 * x1;
  6806. var f1 = 3 * x2 - 6 * x1;
  6807. var f2 = 3 * x1;
  6808. var refinedT = t;
  6809. for (var i = 0; i < 5; i++) {
  6810. var refinedT2 = refinedT * refinedT;
  6811. var refinedT3 = refinedT2 * refinedT;
  6812. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6813. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6814. refinedT -= (x - t) * slope;
  6815. refinedT = Math.min(1, Math.max(0, refinedT));
  6816. }
  6817. // Resolve cubic bezier for the given x
  6818. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6819. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6820. Math.pow(refinedT, 3);
  6821. };
  6822. return BezierCurve;
  6823. }());
  6824. BABYLON.BezierCurve = BezierCurve;
  6825. /**
  6826. * Defines potential orientation for back face culling
  6827. */
  6828. var Orientation;
  6829. (function (Orientation) {
  6830. /**
  6831. * Clockwise
  6832. */
  6833. Orientation[Orientation["CW"] = 0] = "CW";
  6834. /** Counter clockwise */
  6835. Orientation[Orientation["CCW"] = 1] = "CCW";
  6836. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6837. /**
  6838. * Defines angle representation
  6839. */
  6840. var Angle = /** @class */ (function () {
  6841. /**
  6842. * Creates an Angle object of "radians" radians (float).
  6843. */
  6844. function Angle(radians) {
  6845. this._radians = radians;
  6846. if (this._radians < 0.0)
  6847. this._radians += (2.0 * Math.PI);
  6848. }
  6849. /**
  6850. * Get value in degrees
  6851. * @returns the Angle value in degrees (float)
  6852. */
  6853. Angle.prototype.degrees = function () {
  6854. return this._radians * 180.0 / Math.PI;
  6855. };
  6856. /**
  6857. * Get value in radians
  6858. * @returns the Angle value in radians (float)
  6859. */
  6860. Angle.prototype.radians = function () {
  6861. return this._radians;
  6862. };
  6863. /**
  6864. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6865. * @param a defines first vector
  6866. * @param b defines second vector
  6867. * @returns a new Angle
  6868. */
  6869. Angle.BetweenTwoPoints = function (a, b) {
  6870. var delta = b.subtract(a);
  6871. var theta = Math.atan2(delta.y, delta.x);
  6872. return new Angle(theta);
  6873. };
  6874. /**
  6875. * Gets a new Angle object from the given float in radians
  6876. * @param radians defines the angle value in radians
  6877. * @returns a new Angle
  6878. */
  6879. Angle.FromRadians = function (radians) {
  6880. return new Angle(radians);
  6881. };
  6882. /**
  6883. * Gets a new Angle object from the given float in degrees
  6884. * @param degrees defines the angle value in degrees
  6885. * @returns a new Angle
  6886. */
  6887. Angle.FromDegrees = function (degrees) {
  6888. return new Angle(degrees * Math.PI / 180.0);
  6889. };
  6890. return Angle;
  6891. }());
  6892. BABYLON.Angle = Angle;
  6893. var Arc2 = /** @class */ (function () {
  6894. /**
  6895. * Creates an Arc object from the three given points : start, middle and end.
  6896. */
  6897. function Arc2(startPoint, midPoint, endPoint) {
  6898. this.startPoint = startPoint;
  6899. this.midPoint = midPoint;
  6900. this.endPoint = endPoint;
  6901. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6902. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6903. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6904. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6905. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6906. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6907. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6908. var a1 = this.startAngle.degrees();
  6909. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6910. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6911. // angles correction
  6912. if (a2 - a1 > +180.0)
  6913. a2 -= 360.0;
  6914. if (a2 - a1 < -180.0)
  6915. a2 += 360.0;
  6916. if (a3 - a2 > +180.0)
  6917. a3 -= 360.0;
  6918. if (a3 - a2 < -180.0)
  6919. a3 += 360.0;
  6920. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6921. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6922. }
  6923. return Arc2;
  6924. }());
  6925. BABYLON.Arc2 = Arc2;
  6926. var Path2 = /** @class */ (function () {
  6927. /**
  6928. * Creates a Path2 object from the starting 2D coordinates x and y.
  6929. */
  6930. function Path2(x, y) {
  6931. this._points = new Array();
  6932. this._length = 0.0;
  6933. this.closed = false;
  6934. this._points.push(new Vector2(x, y));
  6935. }
  6936. /**
  6937. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6938. * Returns the updated Path2.
  6939. */
  6940. Path2.prototype.addLineTo = function (x, y) {
  6941. if (this.closed) {
  6942. return this;
  6943. }
  6944. var newPoint = new Vector2(x, y);
  6945. var previousPoint = this._points[this._points.length - 1];
  6946. this._points.push(newPoint);
  6947. this._length += newPoint.subtract(previousPoint).length();
  6948. return this;
  6949. };
  6950. /**
  6951. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6952. * Returns the updated Path2.
  6953. */
  6954. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6955. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6956. if (this.closed) {
  6957. return this;
  6958. }
  6959. var startPoint = this._points[this._points.length - 1];
  6960. var midPoint = new Vector2(midX, midY);
  6961. var endPoint = new Vector2(endX, endY);
  6962. var arc = new Arc2(startPoint, midPoint, endPoint);
  6963. var increment = arc.angle.radians() / numberOfSegments;
  6964. if (arc.orientation === Orientation.CW)
  6965. increment *= -1;
  6966. var currentAngle = arc.startAngle.radians() + increment;
  6967. for (var i = 0; i < numberOfSegments; i++) {
  6968. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6969. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6970. this.addLineTo(x, y);
  6971. currentAngle += increment;
  6972. }
  6973. return this;
  6974. };
  6975. /**
  6976. * Closes the Path2.
  6977. * Returns the Path2.
  6978. */
  6979. Path2.prototype.close = function () {
  6980. this.closed = true;
  6981. return this;
  6982. };
  6983. /**
  6984. * Returns the Path2 total length (float).
  6985. */
  6986. Path2.prototype.length = function () {
  6987. var result = this._length;
  6988. if (!this.closed) {
  6989. var lastPoint = this._points[this._points.length - 1];
  6990. var firstPoint = this._points[0];
  6991. result += (firstPoint.subtract(lastPoint).length());
  6992. }
  6993. return result;
  6994. };
  6995. /**
  6996. * Returns the Path2 internal array of points.
  6997. */
  6998. Path2.prototype.getPoints = function () {
  6999. return this._points;
  7000. };
  7001. /**
  7002. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7003. */
  7004. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7005. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7006. return Vector2.Zero();
  7007. }
  7008. var lengthPosition = normalizedLengthPosition * this.length();
  7009. var previousOffset = 0;
  7010. for (var i = 0; i < this._points.length; i++) {
  7011. var j = (i + 1) % this._points.length;
  7012. var a = this._points[i];
  7013. var b = this._points[j];
  7014. var bToA = b.subtract(a);
  7015. var nextOffset = (bToA.length() + previousOffset);
  7016. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7017. var dir = bToA.normalize();
  7018. var localOffset = lengthPosition - previousOffset;
  7019. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7020. }
  7021. previousOffset = nextOffset;
  7022. }
  7023. return Vector2.Zero();
  7024. };
  7025. /**
  7026. * Returns a new Path2 starting at the coordinates (x, y).
  7027. */
  7028. Path2.StartingAt = function (x, y) {
  7029. return new Path2(x, y);
  7030. };
  7031. return Path2;
  7032. }());
  7033. BABYLON.Path2 = Path2;
  7034. var Path3D = /** @class */ (function () {
  7035. /**
  7036. * new Path3D(path, normal, raw)
  7037. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7038. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7039. * path : an array of Vector3, the curve axis of the Path3D
  7040. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7041. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7042. */
  7043. function Path3D(path, firstNormal, raw) {
  7044. if (firstNormal === void 0) { firstNormal = null; }
  7045. this.path = path;
  7046. this._curve = new Array();
  7047. this._distances = new Array();
  7048. this._tangents = new Array();
  7049. this._normals = new Array();
  7050. this._binormals = new Array();
  7051. for (var p = 0; p < path.length; p++) {
  7052. this._curve[p] = path[p].clone(); // hard copy
  7053. }
  7054. this._raw = raw || false;
  7055. this._compute(firstNormal);
  7056. }
  7057. /**
  7058. * Returns the Path3D array of successive Vector3 designing its curve.
  7059. */
  7060. Path3D.prototype.getCurve = function () {
  7061. return this._curve;
  7062. };
  7063. /**
  7064. * Returns an array populated with tangent vectors on each Path3D curve point.
  7065. */
  7066. Path3D.prototype.getTangents = function () {
  7067. return this._tangents;
  7068. };
  7069. /**
  7070. * Returns an array populated with normal vectors on each Path3D curve point.
  7071. */
  7072. Path3D.prototype.getNormals = function () {
  7073. return this._normals;
  7074. };
  7075. /**
  7076. * Returns an array populated with binormal vectors on each Path3D curve point.
  7077. */
  7078. Path3D.prototype.getBinormals = function () {
  7079. return this._binormals;
  7080. };
  7081. /**
  7082. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7083. */
  7084. Path3D.prototype.getDistances = function () {
  7085. return this._distances;
  7086. };
  7087. /**
  7088. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7089. * Returns the same object updated.
  7090. */
  7091. Path3D.prototype.update = function (path, firstNormal) {
  7092. if (firstNormal === void 0) { firstNormal = null; }
  7093. for (var p = 0; p < path.length; p++) {
  7094. this._curve[p].x = path[p].x;
  7095. this._curve[p].y = path[p].y;
  7096. this._curve[p].z = path[p].z;
  7097. }
  7098. this._compute(firstNormal);
  7099. return this;
  7100. };
  7101. // private function compute() : computes tangents, normals and binormals
  7102. Path3D.prototype._compute = function (firstNormal) {
  7103. var l = this._curve.length;
  7104. // first and last tangents
  7105. this._tangents[0] = this._getFirstNonNullVector(0);
  7106. if (!this._raw) {
  7107. this._tangents[0].normalize();
  7108. }
  7109. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7110. if (!this._raw) {
  7111. this._tangents[l - 1].normalize();
  7112. }
  7113. // normals and binormals at first point : arbitrary vector with _normalVector()
  7114. var tg0 = this._tangents[0];
  7115. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7116. this._normals[0] = pp0;
  7117. if (!this._raw) {
  7118. this._normals[0].normalize();
  7119. }
  7120. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7121. if (!this._raw) {
  7122. this._binormals[0].normalize();
  7123. }
  7124. this._distances[0] = 0.0;
  7125. // normals and binormals : next points
  7126. var prev; // previous vector (segment)
  7127. var cur; // current vector (segment)
  7128. var curTang; // current tangent
  7129. // previous normal
  7130. var prevBinor; // previous binormal
  7131. for (var i = 1; i < l; i++) {
  7132. // tangents
  7133. prev = this._getLastNonNullVector(i);
  7134. if (i < l - 1) {
  7135. cur = this._getFirstNonNullVector(i);
  7136. this._tangents[i] = prev.add(cur);
  7137. this._tangents[i].normalize();
  7138. }
  7139. this._distances[i] = this._distances[i - 1] + prev.length();
  7140. // normals and binormals
  7141. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7142. curTang = this._tangents[i];
  7143. prevBinor = this._binormals[i - 1];
  7144. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7145. if (!this._raw) {
  7146. this._normals[i].normalize();
  7147. }
  7148. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7149. if (!this._raw) {
  7150. this._binormals[i].normalize();
  7151. }
  7152. }
  7153. };
  7154. // private function getFirstNonNullVector(index)
  7155. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7156. Path3D.prototype._getFirstNonNullVector = function (index) {
  7157. var i = 1;
  7158. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7159. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7160. i++;
  7161. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7162. }
  7163. return nNVector;
  7164. };
  7165. // private function getLastNonNullVector(index)
  7166. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7167. Path3D.prototype._getLastNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7170. while (nLVector.length() === 0 && index > i + 1) {
  7171. i++;
  7172. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7173. }
  7174. return nLVector;
  7175. };
  7176. // private function normalVector(v0, vt, va) :
  7177. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7178. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7179. Path3D.prototype._normalVector = function (v0, vt, va) {
  7180. var normal0;
  7181. var tgl = vt.length();
  7182. if (tgl === 0.0) {
  7183. tgl = 1.0;
  7184. }
  7185. if (va === undefined || va === null) {
  7186. var point;
  7187. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7188. point = new Vector3(0.0, -1.0, 0.0);
  7189. }
  7190. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7191. point = new Vector3(1.0, 0.0, 0.0);
  7192. }
  7193. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7194. point = new Vector3(0.0, 0.0, 1.0);
  7195. }
  7196. else {
  7197. point = Vector3.Zero();
  7198. }
  7199. normal0 = Vector3.Cross(vt, point);
  7200. }
  7201. else {
  7202. normal0 = Vector3.Cross(vt, va);
  7203. Vector3.CrossToRef(normal0, vt, normal0);
  7204. }
  7205. normal0.normalize();
  7206. return normal0;
  7207. };
  7208. return Path3D;
  7209. }());
  7210. BABYLON.Path3D = Path3D;
  7211. var Curve3 = /** @class */ (function () {
  7212. /**
  7213. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7214. * A Curve3 is designed from a series of successive Vector3.
  7215. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7216. */
  7217. function Curve3(points) {
  7218. this._length = 0.0;
  7219. this._points = points;
  7220. this._length = this._computeLength(points);
  7221. }
  7222. /**
  7223. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7224. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7225. * @param v1 (Vector3) the control point
  7226. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7227. * @param nbPoints (integer) the wanted number of points in the curve
  7228. */
  7229. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7230. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7231. var bez = new Array();
  7232. var equation = function (t, val0, val1, val2) {
  7233. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7234. return res;
  7235. };
  7236. for (var i = 0; i <= nbPoints; i++) {
  7237. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7238. }
  7239. return new Curve3(bez);
  7240. };
  7241. /**
  7242. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7243. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7244. * @param v1 (Vector3) the first control point
  7245. * @param v2 (Vector3) the second control point
  7246. * @param v3 (Vector3) the end point of the Cubic Bezier
  7247. * @param nbPoints (integer) the wanted number of points in the curve
  7248. */
  7249. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7250. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7251. var bez = new Array();
  7252. var equation = function (t, val0, val1, val2, val3) {
  7253. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7254. return res;
  7255. };
  7256. for (var i = 0; i <= nbPoints; i++) {
  7257. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7258. }
  7259. return new Curve3(bez);
  7260. };
  7261. /**
  7262. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7263. * @param p1 (Vector3) the origin point of the Hermite Spline
  7264. * @param t1 (Vector3) the tangent vector at the origin point
  7265. * @param p2 (Vector3) the end point of the Hermite Spline
  7266. * @param t2 (Vector3) the tangent vector at the end point
  7267. * @param nbPoints (integer) the wanted number of points in the curve
  7268. */
  7269. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7270. var hermite = new Array();
  7271. var step = 1.0 / nbPoints;
  7272. for (var i = 0; i <= nbPoints; i++) {
  7273. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7274. }
  7275. return new Curve3(hermite);
  7276. };
  7277. /**
  7278. * Returns a Curve3 object along a CatmullRom Spline curve :
  7279. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7280. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7281. */
  7282. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7283. var totalPoints = new Array();
  7284. totalPoints.push(points[0].clone());
  7285. Array.prototype.push.apply(totalPoints, points);
  7286. totalPoints.push(points[points.length - 1].clone());
  7287. var catmullRom = new Array();
  7288. var step = 1.0 / nbPoints;
  7289. var amount = 0.0;
  7290. for (var i = 0; i < totalPoints.length - 3; i++) {
  7291. amount = 0;
  7292. for (var c = 0; c < nbPoints; c++) {
  7293. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7294. amount += step;
  7295. }
  7296. }
  7297. i--;
  7298. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7299. return new Curve3(catmullRom);
  7300. };
  7301. /**
  7302. * Returns the Curve3 stored array of successive Vector3
  7303. */
  7304. Curve3.prototype.getPoints = function () {
  7305. return this._points;
  7306. };
  7307. /**
  7308. * Returns the computed length (float) of the curve.
  7309. */
  7310. Curve3.prototype.length = function () {
  7311. return this._length;
  7312. };
  7313. /**
  7314. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7315. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7316. * curveA and curveB keep unchanged.
  7317. */
  7318. Curve3.prototype.continue = function (curve) {
  7319. var lastPoint = this._points[this._points.length - 1];
  7320. var continuedPoints = this._points.slice();
  7321. var curvePoints = curve.getPoints();
  7322. for (var i = 1; i < curvePoints.length; i++) {
  7323. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7324. }
  7325. var continuedCurve = new Curve3(continuedPoints);
  7326. return continuedCurve;
  7327. };
  7328. Curve3.prototype._computeLength = function (path) {
  7329. var l = 0;
  7330. for (var i = 1; i < path.length; i++) {
  7331. l += (path[i].subtract(path[i - 1])).length();
  7332. }
  7333. return l;
  7334. };
  7335. return Curve3;
  7336. }());
  7337. BABYLON.Curve3 = Curve3;
  7338. // Vertex formats
  7339. var PositionNormalVertex = /** @class */ (function () {
  7340. function PositionNormalVertex(position, normal) {
  7341. if (position === void 0) { position = Vector3.Zero(); }
  7342. if (normal === void 0) { normal = Vector3.Up(); }
  7343. this.position = position;
  7344. this.normal = normal;
  7345. }
  7346. PositionNormalVertex.prototype.clone = function () {
  7347. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7348. };
  7349. return PositionNormalVertex;
  7350. }());
  7351. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7352. var PositionNormalTextureVertex = /** @class */ (function () {
  7353. function PositionNormalTextureVertex(position, normal, uv) {
  7354. if (position === void 0) { position = Vector3.Zero(); }
  7355. if (normal === void 0) { normal = Vector3.Up(); }
  7356. if (uv === void 0) { uv = Vector2.Zero(); }
  7357. this.position = position;
  7358. this.normal = normal;
  7359. this.uv = uv;
  7360. }
  7361. PositionNormalTextureVertex.prototype.clone = function () {
  7362. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7363. };
  7364. return PositionNormalTextureVertex;
  7365. }());
  7366. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7367. // Temporary pre-allocated objects for engine internal use
  7368. // usage in any internal function :
  7369. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7370. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7371. var Tmp = /** @class */ (function () {
  7372. function Tmp() {
  7373. }
  7374. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7375. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7376. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7377. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7378. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7379. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7380. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7381. Matrix.Zero(), Matrix.Zero(),
  7382. Matrix.Zero(), Matrix.Zero(),
  7383. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7384. return Tmp;
  7385. }());
  7386. BABYLON.Tmp = Tmp;
  7387. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7388. var MathTmp = /** @class */ (function () {
  7389. function MathTmp() {
  7390. }
  7391. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7392. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7393. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7394. return MathTmp;
  7395. }());
  7396. })(BABYLON || (BABYLON = {}));
  7397. //# sourceMappingURL=babylon.math.js.map
  7398. var BABYLON;
  7399. (function (BABYLON) {
  7400. var Scalar = /** @class */ (function () {
  7401. function Scalar() {
  7402. }
  7403. /**
  7404. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7405. */
  7406. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7407. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7408. var num = a - b;
  7409. return -epsilon <= num && num <= epsilon;
  7410. };
  7411. /**
  7412. * Returns a string : the upper case translation of the number i to hexadecimal.
  7413. */
  7414. Scalar.ToHex = function (i) {
  7415. var str = i.toString(16);
  7416. if (i <= 15) {
  7417. return ("0" + str).toUpperCase();
  7418. }
  7419. return str.toUpperCase();
  7420. };
  7421. /**
  7422. * Returns -1 if value is negative and +1 is value is positive.
  7423. * Returns the value itself if it's equal to zero.
  7424. */
  7425. Scalar.Sign = function (value) {
  7426. value = +value; // convert to a number
  7427. if (value === 0 || isNaN(value))
  7428. return value;
  7429. return value > 0 ? 1 : -1;
  7430. };
  7431. /**
  7432. * Returns the value itself if it's between min and max.
  7433. * Returns min if the value is lower than min.
  7434. * Returns max if the value is greater than max.
  7435. */
  7436. Scalar.Clamp = function (value, min, max) {
  7437. if (min === void 0) { min = 0; }
  7438. if (max === void 0) { max = 1; }
  7439. return Math.min(max, Math.max(min, value));
  7440. };
  7441. /**
  7442. * Returns the log2 of value.
  7443. */
  7444. Scalar.Log2 = function (value) {
  7445. return Math.log(value) * Math.LOG2E;
  7446. };
  7447. /**
  7448. * Loops the value, so that it is never larger than length and never smaller than 0.
  7449. *
  7450. * This is similar to the modulo operator but it works with floating point numbers.
  7451. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7452. * With t = 5 and length = 2.5, the result would be 0.0.
  7453. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7454. */
  7455. Scalar.Repeat = function (value, length) {
  7456. return value - Math.floor(value / length) * length;
  7457. };
  7458. /**
  7459. * Normalize the value between 0.0 and 1.0 using min and max values
  7460. */
  7461. Scalar.Normalize = function (value, min, max) {
  7462. return (value - min) / (max - min);
  7463. };
  7464. /**
  7465. * Denormalize the value from 0.0 and 1.0 using min and max values
  7466. */
  7467. Scalar.Denormalize = function (normalized, min, max) {
  7468. return (normalized * (max - min) + min);
  7469. };
  7470. /**
  7471. * Calculates the shortest difference between two given angles given in degrees.
  7472. */
  7473. Scalar.DeltaAngle = function (current, target) {
  7474. var num = Scalar.Repeat(target - current, 360.0);
  7475. if (num > 180.0) {
  7476. num -= 360.0;
  7477. }
  7478. return num;
  7479. };
  7480. /**
  7481. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7482. *
  7483. * The returned value will move back and forth between 0 and length
  7484. */
  7485. Scalar.PingPong = function (tx, length) {
  7486. var t = Scalar.Repeat(tx, length * 2.0);
  7487. return length - Math.abs(t - length);
  7488. };
  7489. /**
  7490. * Interpolates between min and max with smoothing at the limits.
  7491. *
  7492. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7493. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7494. */
  7495. Scalar.SmoothStep = function (from, to, tx) {
  7496. var t = Scalar.Clamp(tx);
  7497. t = -2.0 * t * t * t + 3.0 * t * t;
  7498. return to * t + from * (1.0 - t);
  7499. };
  7500. /**
  7501. * Moves a value current towards target.
  7502. *
  7503. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7504. * Negative values of maxDelta pushes the value away from target.
  7505. */
  7506. Scalar.MoveTowards = function (current, target, maxDelta) {
  7507. var result = 0;
  7508. if (Math.abs(target - current) <= maxDelta) {
  7509. result = target;
  7510. }
  7511. else {
  7512. result = current + Scalar.Sign(target - current) * maxDelta;
  7513. }
  7514. return result;
  7515. };
  7516. /**
  7517. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7518. *
  7519. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7520. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7521. */
  7522. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7523. var num = Scalar.DeltaAngle(current, target);
  7524. var result = 0;
  7525. if (-maxDelta < num && num < maxDelta) {
  7526. result = target;
  7527. }
  7528. else {
  7529. target = current + num;
  7530. result = Scalar.MoveTowards(current, target, maxDelta);
  7531. }
  7532. return result;
  7533. };
  7534. /**
  7535. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7536. */
  7537. Scalar.Lerp = function (start, end, amount) {
  7538. return start + ((end - start) * amount);
  7539. };
  7540. /**
  7541. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7542. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7543. */
  7544. Scalar.LerpAngle = function (start, end, amount) {
  7545. var num = Scalar.Repeat(end - start, 360.0);
  7546. if (num > 180.0) {
  7547. num -= 360.0;
  7548. }
  7549. return start + num * Scalar.Clamp(amount);
  7550. };
  7551. /**
  7552. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7553. */
  7554. Scalar.InverseLerp = function (a, b, value) {
  7555. var result = 0;
  7556. if (a != b) {
  7557. result = Scalar.Clamp((value - a) / (b - a));
  7558. }
  7559. else {
  7560. result = 0.0;
  7561. }
  7562. return result;
  7563. };
  7564. /**
  7565. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7566. */
  7567. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7568. var squared = amount * amount;
  7569. var cubed = amount * squared;
  7570. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7571. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7572. var part3 = (cubed - (2.0 * squared)) + amount;
  7573. var part4 = cubed - squared;
  7574. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7575. };
  7576. /**
  7577. * Returns a random float number between and min and max values
  7578. */
  7579. Scalar.RandomRange = function (min, max) {
  7580. if (min === max)
  7581. return min;
  7582. return ((Math.random() * (max - min)) + min);
  7583. };
  7584. /**
  7585. * This function returns percentage of a number in a given range.
  7586. *
  7587. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7588. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7589. */
  7590. Scalar.RangeToPercent = function (number, min, max) {
  7591. return ((number - min) / (max - min));
  7592. };
  7593. /**
  7594. * This function returns number that corresponds to the percentage in a given range.
  7595. *
  7596. * PercentToRange(0.34,0,100) will return 34.
  7597. */
  7598. Scalar.PercentToRange = function (percent, min, max) {
  7599. return ((max - min) * percent + min);
  7600. };
  7601. /**
  7602. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7603. * @param angle The angle to normalize in radian.
  7604. * @return The converted angle.
  7605. */
  7606. Scalar.NormalizeRadians = function (angle) {
  7607. // More precise but slower version kept for reference.
  7608. // angle = angle % Tools.TwoPi;
  7609. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7610. //if (angle > Math.PI) {
  7611. // angle -= Tools.TwoPi;
  7612. //}
  7613. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7614. return angle;
  7615. };
  7616. /**
  7617. * Two pi constants convenient for computation.
  7618. */
  7619. Scalar.TwoPi = Math.PI * 2;
  7620. return Scalar;
  7621. }());
  7622. BABYLON.Scalar = Scalar;
  7623. })(BABYLON || (BABYLON = {}));
  7624. //# sourceMappingURL=babylon.math.scalar.js.map
  7625. //# sourceMappingURL=babylon.mixins.js.map
  7626. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7627. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7628. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7629. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7630. //# sourceMappingURL=babylon.webgl2.js.map
  7631. var BABYLON;
  7632. (function (BABYLON) {
  7633. var __decoratorInitialStore = {};
  7634. var __mergedStore = {};
  7635. var _copySource = function (creationFunction, source, instanciate) {
  7636. var destination = creationFunction();
  7637. // Tags
  7638. if (BABYLON.Tags) {
  7639. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7640. }
  7641. var classStore = getMergedStore(destination);
  7642. // Properties
  7643. for (var property in classStore) {
  7644. var propertyDescriptor = classStore[property];
  7645. var sourceProperty = source[property];
  7646. var propertyType = propertyDescriptor.type;
  7647. if (sourceProperty !== undefined && sourceProperty !== null) {
  7648. switch (propertyType) {
  7649. case 0: // Value
  7650. case 6: // Mesh reference
  7651. case 11: // Camera reference
  7652. destination[property] = sourceProperty;
  7653. break;
  7654. case 1: // Texture
  7655. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7656. break;
  7657. case 2: // Color3
  7658. case 3: // FresnelParameters
  7659. case 4: // Vector2
  7660. case 5: // Vector3
  7661. case 7: // Color Curves
  7662. case 10: // Quaternion
  7663. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7664. break;
  7665. }
  7666. }
  7667. }
  7668. return destination;
  7669. };
  7670. function getDirectStore(target) {
  7671. var classKey = target.getClassName();
  7672. if (!__decoratorInitialStore[classKey]) {
  7673. __decoratorInitialStore[classKey] = {};
  7674. }
  7675. return __decoratorInitialStore[classKey];
  7676. }
  7677. /**
  7678. * Return the list of properties flagged as serializable
  7679. * @param target: host object
  7680. */
  7681. function getMergedStore(target) {
  7682. var classKey = target.getClassName();
  7683. if (__mergedStore[classKey]) {
  7684. return __mergedStore[classKey];
  7685. }
  7686. __mergedStore[classKey] = {};
  7687. var store = __mergedStore[classKey];
  7688. var currentTarget = target;
  7689. var currentKey = classKey;
  7690. while (currentKey) {
  7691. var initialStore = __decoratorInitialStore[currentKey];
  7692. for (var property in initialStore) {
  7693. store[property] = initialStore[property];
  7694. }
  7695. var parent_1 = void 0;
  7696. var done = false;
  7697. do {
  7698. parent_1 = Object.getPrototypeOf(currentTarget);
  7699. if (!parent_1.getClassName) {
  7700. done = true;
  7701. break;
  7702. }
  7703. if (parent_1.getClassName() !== currentKey) {
  7704. break;
  7705. }
  7706. currentTarget = parent_1;
  7707. } while (parent_1);
  7708. if (done) {
  7709. break;
  7710. }
  7711. currentKey = parent_1.getClassName();
  7712. currentTarget = parent_1;
  7713. }
  7714. return store;
  7715. }
  7716. function generateSerializableMember(type, sourceName) {
  7717. return function (target, propertyKey) {
  7718. var classStore = getDirectStore(target);
  7719. if (!classStore[propertyKey]) {
  7720. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7721. }
  7722. };
  7723. }
  7724. function generateExpandMember(setCallback, targetKey) {
  7725. if (targetKey === void 0) { targetKey = null; }
  7726. return function (target, propertyKey) {
  7727. var key = targetKey || ("_" + propertyKey);
  7728. Object.defineProperty(target, propertyKey, {
  7729. get: function () {
  7730. return this[key];
  7731. },
  7732. set: function (value) {
  7733. if (this[key] === value) {
  7734. return;
  7735. }
  7736. this[key] = value;
  7737. target[setCallback].apply(this);
  7738. },
  7739. enumerable: true,
  7740. configurable: true
  7741. });
  7742. };
  7743. }
  7744. function expandToProperty(callback, targetKey) {
  7745. if (targetKey === void 0) { targetKey = null; }
  7746. return generateExpandMember(callback, targetKey);
  7747. }
  7748. BABYLON.expandToProperty = expandToProperty;
  7749. function serialize(sourceName) {
  7750. return generateSerializableMember(0, sourceName); // value member
  7751. }
  7752. BABYLON.serialize = serialize;
  7753. function serializeAsTexture(sourceName) {
  7754. return generateSerializableMember(1, sourceName); // texture member
  7755. }
  7756. BABYLON.serializeAsTexture = serializeAsTexture;
  7757. function serializeAsColor3(sourceName) {
  7758. return generateSerializableMember(2, sourceName); // color3 member
  7759. }
  7760. BABYLON.serializeAsColor3 = serializeAsColor3;
  7761. function serializeAsFresnelParameters(sourceName) {
  7762. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7763. }
  7764. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7765. function serializeAsVector2(sourceName) {
  7766. return generateSerializableMember(4, sourceName); // vector2 member
  7767. }
  7768. BABYLON.serializeAsVector2 = serializeAsVector2;
  7769. function serializeAsVector3(sourceName) {
  7770. return generateSerializableMember(5, sourceName); // vector3 member
  7771. }
  7772. BABYLON.serializeAsVector3 = serializeAsVector3;
  7773. function serializeAsMeshReference(sourceName) {
  7774. return generateSerializableMember(6, sourceName); // mesh reference member
  7775. }
  7776. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7777. function serializeAsColorCurves(sourceName) {
  7778. return generateSerializableMember(7, sourceName); // color curves
  7779. }
  7780. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7781. function serializeAsColor4(sourceName) {
  7782. return generateSerializableMember(8, sourceName); // color 4
  7783. }
  7784. BABYLON.serializeAsColor4 = serializeAsColor4;
  7785. function serializeAsImageProcessingConfiguration(sourceName) {
  7786. return generateSerializableMember(9, sourceName); // image processing
  7787. }
  7788. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7789. function serializeAsQuaternion(sourceName) {
  7790. return generateSerializableMember(10, sourceName); // quaternion member
  7791. }
  7792. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7793. /**
  7794. * Decorator used to define property that can be serialized as reference to a camera
  7795. * @param sourceName defines the name of the property to decorate
  7796. */
  7797. function serializeAsCameraReference(sourceName) {
  7798. return generateSerializableMember(11, sourceName); // camera reference member
  7799. }
  7800. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7801. var SerializationHelper = /** @class */ (function () {
  7802. function SerializationHelper() {
  7803. }
  7804. SerializationHelper.Serialize = function (entity, serializationObject) {
  7805. if (!serializationObject) {
  7806. serializationObject = {};
  7807. }
  7808. // Tags
  7809. if (BABYLON.Tags) {
  7810. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7811. }
  7812. var serializedProperties = getMergedStore(entity);
  7813. // Properties
  7814. for (var property in serializedProperties) {
  7815. var propertyDescriptor = serializedProperties[property];
  7816. var targetPropertyName = propertyDescriptor.sourceName || property;
  7817. var propertyType = propertyDescriptor.type;
  7818. var sourceProperty = entity[property];
  7819. if (sourceProperty !== undefined && sourceProperty !== null) {
  7820. switch (propertyType) {
  7821. case 0: // Value
  7822. serializationObject[targetPropertyName] = sourceProperty;
  7823. break;
  7824. case 1: // Texture
  7825. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7826. break;
  7827. case 2: // Color3
  7828. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7829. break;
  7830. case 3: // FresnelParameters
  7831. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7832. break;
  7833. case 4: // Vector2
  7834. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7835. break;
  7836. case 5: // Vector3
  7837. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7838. break;
  7839. case 6: // Mesh reference
  7840. serializationObject[targetPropertyName] = sourceProperty.id;
  7841. break;
  7842. case 7: // Color Curves
  7843. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7844. break;
  7845. case 8: // Color 4
  7846. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7847. break;
  7848. case 9: // Image Processing
  7849. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7850. break;
  7851. case 10: // Quaternion
  7852. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7853. break;
  7854. case 11: // Camera reference
  7855. serializationObject[targetPropertyName] = sourceProperty.id;
  7856. break;
  7857. }
  7858. }
  7859. }
  7860. return serializationObject;
  7861. };
  7862. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7863. if (rootUrl === void 0) { rootUrl = null; }
  7864. var destination = creationFunction();
  7865. if (!rootUrl) {
  7866. rootUrl = "";
  7867. }
  7868. // Tags
  7869. if (BABYLON.Tags) {
  7870. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7871. }
  7872. var classStore = getMergedStore(destination);
  7873. // Properties
  7874. for (var property in classStore) {
  7875. var propertyDescriptor = classStore[property];
  7876. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7877. var propertyType = propertyDescriptor.type;
  7878. if (sourceProperty !== undefined && sourceProperty !== null) {
  7879. var dest = destination;
  7880. switch (propertyType) {
  7881. case 0: // Value
  7882. dest[property] = sourceProperty;
  7883. break;
  7884. case 1: // Texture
  7885. if (scene) {
  7886. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7887. }
  7888. break;
  7889. case 2: // Color3
  7890. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7891. break;
  7892. case 3: // FresnelParameters
  7893. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7894. break;
  7895. case 4: // Vector2
  7896. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7897. break;
  7898. case 5: // Vector3
  7899. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7900. break;
  7901. case 6: // Mesh reference
  7902. if (scene) {
  7903. dest[property] = scene.getLastMeshByID(sourceProperty);
  7904. }
  7905. break;
  7906. case 7: // Color Curves
  7907. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7908. break;
  7909. case 8: // Color 4
  7910. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7911. break;
  7912. case 9: // Image Processing
  7913. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7914. break;
  7915. case 10: // Quaternion
  7916. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7917. break;
  7918. case 11: // Camera reference
  7919. if (scene) {
  7920. dest[property] = scene.getCameraByID(sourceProperty);
  7921. }
  7922. break;
  7923. }
  7924. }
  7925. }
  7926. return destination;
  7927. };
  7928. SerializationHelper.Clone = function (creationFunction, source) {
  7929. return _copySource(creationFunction, source, false);
  7930. };
  7931. SerializationHelper.Instanciate = function (creationFunction, source) {
  7932. return _copySource(creationFunction, source, true);
  7933. };
  7934. return SerializationHelper;
  7935. }());
  7936. BABYLON.SerializationHelper = SerializationHelper;
  7937. })(BABYLON || (BABYLON = {}));
  7938. //# sourceMappingURL=babylon.decorators.js.map
  7939. var BABYLON;
  7940. (function (BABYLON) {
  7941. /**
  7942. * Wrapper class for promise with external resolve and reject.
  7943. */
  7944. var Deferred = /** @class */ (function () {
  7945. /**
  7946. * Constructor for this deferred object.
  7947. */
  7948. function Deferred() {
  7949. var _this = this;
  7950. this.promise = new Promise(function (resolve, reject) {
  7951. _this._resolve = resolve;
  7952. _this._reject = reject;
  7953. });
  7954. }
  7955. Object.defineProperty(Deferred.prototype, "resolve", {
  7956. /**
  7957. * The resolve method of the promise associated with this deferred object.
  7958. */
  7959. get: function () {
  7960. return this._resolve;
  7961. },
  7962. enumerable: true,
  7963. configurable: true
  7964. });
  7965. Object.defineProperty(Deferred.prototype, "reject", {
  7966. /**
  7967. * The reject method of the promise associated with this deferred object.
  7968. */
  7969. get: function () {
  7970. return this._reject;
  7971. },
  7972. enumerable: true,
  7973. configurable: true
  7974. });
  7975. return Deferred;
  7976. }());
  7977. BABYLON.Deferred = Deferred;
  7978. })(BABYLON || (BABYLON = {}));
  7979. //# sourceMappingURL=babylon.deferred.js.map
  7980. var BABYLON;
  7981. (function (BABYLON) {
  7982. /**
  7983. * A class serves as a medium between the observable and its observers
  7984. */
  7985. var EventState = /** @class */ (function () {
  7986. /**
  7987. * Create a new EventState
  7988. * @param mask defines the mask associated with this state
  7989. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7990. * @param target defines the original target of the state
  7991. * @param currentTarget defines the current target of the state
  7992. */
  7993. function EventState(mask, skipNextObservers, target, currentTarget) {
  7994. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7995. this.initalize(mask, skipNextObservers, target, currentTarget);
  7996. }
  7997. /**
  7998. * Initialize the current event state
  7999. * @param mask defines the mask associated with this state
  8000. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8001. * @param target defines the original target of the state
  8002. * @param currentTarget defines the current target of the state
  8003. * @returns the current event state
  8004. */
  8005. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8006. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8007. this.mask = mask;
  8008. this.skipNextObservers = skipNextObservers;
  8009. this.target = target;
  8010. this.currentTarget = currentTarget;
  8011. return this;
  8012. };
  8013. return EventState;
  8014. }());
  8015. BABYLON.EventState = EventState;
  8016. /**
  8017. * Represent an Observer registered to a given Observable object.
  8018. */
  8019. var Observer = /** @class */ (function () {
  8020. /**
  8021. * Creates a new observer
  8022. * @param callback defines the callback to call when the observer is notified
  8023. * @param mask defines the mask of the observer (used to filter notifications)
  8024. * @param scope defines the current scope used to restore the JS context
  8025. */
  8026. function Observer(
  8027. /**
  8028. * Defines the callback to call when the observer is notified
  8029. */
  8030. callback,
  8031. /**
  8032. * Defines the mask of the observer (used to filter notifications)
  8033. */
  8034. mask,
  8035. /**
  8036. * Defines the current scope used to restore the JS context
  8037. */
  8038. scope) {
  8039. if (scope === void 0) { scope = null; }
  8040. this.callback = callback;
  8041. this.mask = mask;
  8042. this.scope = scope;
  8043. /** @hidden */
  8044. this._willBeUnregistered = false;
  8045. /**
  8046. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8047. */
  8048. this.unregisterOnNextCall = false;
  8049. }
  8050. return Observer;
  8051. }());
  8052. BABYLON.Observer = Observer;
  8053. /**
  8054. * Represent a list of observers registered to multiple Observables object.
  8055. */
  8056. var MultiObserver = /** @class */ (function () {
  8057. function MultiObserver() {
  8058. }
  8059. /**
  8060. * Release associated resources
  8061. */
  8062. MultiObserver.prototype.dispose = function () {
  8063. if (this._observers && this._observables) {
  8064. for (var index = 0; index < this._observers.length; index++) {
  8065. this._observables[index].remove(this._observers[index]);
  8066. }
  8067. }
  8068. this._observers = null;
  8069. this._observables = null;
  8070. };
  8071. /**
  8072. * Raise a callback when one of the observable will notify
  8073. * @param observables defines a list of observables to watch
  8074. * @param callback defines the callback to call on notification
  8075. * @param mask defines the mask used to filter notifications
  8076. * @param scope defines the current scope used to restore the JS context
  8077. * @returns the new MultiObserver
  8078. */
  8079. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8080. if (mask === void 0) { mask = -1; }
  8081. if (scope === void 0) { scope = null; }
  8082. var result = new MultiObserver();
  8083. result._observers = new Array();
  8084. result._observables = observables;
  8085. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8086. var observable = observables_1[_i];
  8087. var observer = observable.add(callback, mask, false, scope);
  8088. if (observer) {
  8089. result._observers.push(observer);
  8090. }
  8091. }
  8092. return result;
  8093. };
  8094. return MultiObserver;
  8095. }());
  8096. BABYLON.MultiObserver = MultiObserver;
  8097. /**
  8098. * The Observable class is a simple implementation of the Observable pattern.
  8099. *
  8100. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8101. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8102. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8103. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8104. */
  8105. var Observable = /** @class */ (function () {
  8106. /**
  8107. * Creates a new observable
  8108. * @param onObserverAdded defines a callback to call when a new observer is added
  8109. */
  8110. function Observable(onObserverAdded) {
  8111. this._observers = new Array();
  8112. this._eventState = new EventState(0);
  8113. if (onObserverAdded) {
  8114. this._onObserverAdded = onObserverAdded;
  8115. }
  8116. }
  8117. /**
  8118. * Create a new Observer with the specified callback
  8119. * @param callback the callback that will be executed for that Observer
  8120. * @param mask the mask used to filter observers
  8121. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8122. * @param scope optional scope for the callback to be called from
  8123. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8124. * @returns the new observer created for the callback
  8125. */
  8126. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8127. if (mask === void 0) { mask = -1; }
  8128. if (insertFirst === void 0) { insertFirst = false; }
  8129. if (scope === void 0) { scope = null; }
  8130. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8131. if (!callback) {
  8132. return null;
  8133. }
  8134. var observer = new Observer(callback, mask, scope);
  8135. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8136. if (insertFirst) {
  8137. this._observers.unshift(observer);
  8138. }
  8139. else {
  8140. this._observers.push(observer);
  8141. }
  8142. if (this._onObserverAdded) {
  8143. this._onObserverAdded(observer);
  8144. }
  8145. return observer;
  8146. };
  8147. /**
  8148. * Remove an Observer from the Observable object
  8149. * @param observer the instance of the Observer to remove
  8150. * @returns false if it doesn't belong to this Observable
  8151. */
  8152. Observable.prototype.remove = function (observer) {
  8153. if (!observer) {
  8154. return false;
  8155. }
  8156. var index = this._observers.indexOf(observer);
  8157. if (index !== -1) {
  8158. this._observers.splice(index, 1);
  8159. return true;
  8160. }
  8161. return false;
  8162. };
  8163. /**
  8164. * Remove a callback from the Observable object
  8165. * @param callback the callback to remove
  8166. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8167. * @returns false if it doesn't belong to this Observable
  8168. */
  8169. Observable.prototype.removeCallback = function (callback, scope) {
  8170. for (var index = 0; index < this._observers.length; index++) {
  8171. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8172. this._observers.splice(index, 1);
  8173. return true;
  8174. }
  8175. }
  8176. return false;
  8177. };
  8178. Observable.prototype._deferUnregister = function (observer) {
  8179. var _this = this;
  8180. observer.unregisterOnNextCall = false;
  8181. observer._willBeUnregistered = true;
  8182. BABYLON.Tools.SetImmediate(function () {
  8183. _this.remove(observer);
  8184. });
  8185. };
  8186. /**
  8187. * Notify all Observers by calling their respective callback with the given data
  8188. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8189. * @param eventData defines the data to send to all observers
  8190. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8191. * @param target defines the original target of the state
  8192. * @param currentTarget defines the current target of the state
  8193. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8194. */
  8195. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8196. if (mask === void 0) { mask = -1; }
  8197. if (!this._observers.length) {
  8198. return true;
  8199. }
  8200. var state = this._eventState;
  8201. state.mask = mask;
  8202. state.target = target;
  8203. state.currentTarget = currentTarget;
  8204. state.skipNextObservers = false;
  8205. state.lastReturnValue = eventData;
  8206. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8207. var obs = _a[_i];
  8208. if (obs._willBeUnregistered) {
  8209. continue;
  8210. }
  8211. if (obs.mask & mask) {
  8212. if (obs.scope) {
  8213. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8214. }
  8215. else {
  8216. state.lastReturnValue = obs.callback(eventData, state);
  8217. }
  8218. if (obs.unregisterOnNextCall) {
  8219. this._deferUnregister(obs);
  8220. }
  8221. }
  8222. if (state.skipNextObservers) {
  8223. return false;
  8224. }
  8225. }
  8226. return true;
  8227. };
  8228. /**
  8229. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8230. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8231. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8232. * and it is crucial that all callbacks will be executed.
  8233. * The order of the callbacks is kept, callbacks are not executed parallel.
  8234. *
  8235. * @param eventData The data to be sent to each callback
  8236. * @param mask is used to filter observers defaults to -1
  8237. * @param target defines the callback target (see EventState)
  8238. * @param currentTarget defines he current object in the bubbling phase
  8239. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8240. */
  8241. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8242. var _this = this;
  8243. if (mask === void 0) { mask = -1; }
  8244. // create an empty promise
  8245. var p = Promise.resolve(eventData);
  8246. // no observers? return this promise.
  8247. if (!this._observers.length) {
  8248. return p;
  8249. }
  8250. var state = this._eventState;
  8251. state.mask = mask;
  8252. state.target = target;
  8253. state.currentTarget = currentTarget;
  8254. state.skipNextObservers = false;
  8255. // execute one callback after another (not using Promise.all, the order is important)
  8256. this._observers.forEach(function (obs) {
  8257. if (state.skipNextObservers) {
  8258. return;
  8259. }
  8260. if (obs._willBeUnregistered) {
  8261. return;
  8262. }
  8263. if (obs.mask & mask) {
  8264. if (obs.scope) {
  8265. p = p.then(function (lastReturnedValue) {
  8266. state.lastReturnValue = lastReturnedValue;
  8267. return obs.callback.apply(obs.scope, [eventData, state]);
  8268. });
  8269. }
  8270. else {
  8271. p = p.then(function (lastReturnedValue) {
  8272. state.lastReturnValue = lastReturnedValue;
  8273. return obs.callback(eventData, state);
  8274. });
  8275. }
  8276. if (obs.unregisterOnNextCall) {
  8277. _this._deferUnregister(obs);
  8278. }
  8279. }
  8280. });
  8281. // return the eventData
  8282. return p.then(function () { return eventData; });
  8283. };
  8284. /**
  8285. * Notify a specific observer
  8286. * @param observer defines the observer to notify
  8287. * @param eventData defines the data to be sent to each callback
  8288. * @param mask is used to filter observers defaults to -1
  8289. */
  8290. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8291. if (mask === void 0) { mask = -1; }
  8292. var state = this._eventState;
  8293. state.mask = mask;
  8294. state.skipNextObservers = false;
  8295. observer.callback(eventData, state);
  8296. };
  8297. /**
  8298. * Gets a boolean indicating if the observable has at least one observer
  8299. * @returns true is the Observable has at least one Observer registered
  8300. */
  8301. Observable.prototype.hasObservers = function () {
  8302. return this._observers.length > 0;
  8303. };
  8304. /**
  8305. * Clear the list of observers
  8306. */
  8307. Observable.prototype.clear = function () {
  8308. this._observers = new Array();
  8309. this._onObserverAdded = null;
  8310. };
  8311. /**
  8312. * Clone the current observable
  8313. * @returns a new observable
  8314. */
  8315. Observable.prototype.clone = function () {
  8316. var result = new Observable();
  8317. result._observers = this._observers.slice(0);
  8318. return result;
  8319. };
  8320. /**
  8321. * Does this observable handles observer registered with a given mask
  8322. * @param mask defines the mask to be tested
  8323. * @return whether or not one observer registered with the given mask is handeled
  8324. **/
  8325. Observable.prototype.hasSpecificMask = function (mask) {
  8326. if (mask === void 0) { mask = -1; }
  8327. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8328. var obs = _a[_i];
  8329. if (obs.mask & mask || obs.mask === mask) {
  8330. return true;
  8331. }
  8332. }
  8333. return false;
  8334. };
  8335. return Observable;
  8336. }());
  8337. BABYLON.Observable = Observable;
  8338. })(BABYLON || (BABYLON = {}));
  8339. //# sourceMappingURL=babylon.observable.js.map
  8340. var BABYLON;
  8341. (function (BABYLON) {
  8342. var SmartArray = /** @class */ (function () {
  8343. function SmartArray(capacity) {
  8344. this.length = 0;
  8345. this.data = new Array(capacity);
  8346. this._id = SmartArray._GlobalId++;
  8347. }
  8348. SmartArray.prototype.push = function (value) {
  8349. this.data[this.length++] = value;
  8350. if (this.length > this.data.length) {
  8351. this.data.length *= 2;
  8352. }
  8353. };
  8354. SmartArray.prototype.forEach = function (func) {
  8355. for (var index = 0; index < this.length; index++) {
  8356. func(this.data[index]);
  8357. }
  8358. };
  8359. SmartArray.prototype.sort = function (compareFn) {
  8360. this.data.sort(compareFn);
  8361. };
  8362. SmartArray.prototype.reset = function () {
  8363. this.length = 0;
  8364. };
  8365. SmartArray.prototype.dispose = function () {
  8366. this.reset();
  8367. if (this.data) {
  8368. this.data.length = 0;
  8369. this.data = [];
  8370. }
  8371. };
  8372. SmartArray.prototype.concat = function (array) {
  8373. if (array.length === 0) {
  8374. return;
  8375. }
  8376. if (this.length + array.length > this.data.length) {
  8377. this.data.length = (this.length + array.length) * 2;
  8378. }
  8379. for (var index = 0; index < array.length; index++) {
  8380. this.data[this.length++] = (array.data || array)[index];
  8381. }
  8382. };
  8383. SmartArray.prototype.indexOf = function (value) {
  8384. var position = this.data.indexOf(value);
  8385. if (position >= this.length) {
  8386. return -1;
  8387. }
  8388. return position;
  8389. };
  8390. SmartArray.prototype.contains = function (value) {
  8391. return this.data.indexOf(value) !== -1;
  8392. };
  8393. // Statics
  8394. SmartArray._GlobalId = 0;
  8395. return SmartArray;
  8396. }());
  8397. BABYLON.SmartArray = SmartArray;
  8398. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8399. __extends(SmartArrayNoDuplicate, _super);
  8400. function SmartArrayNoDuplicate() {
  8401. var _this = _super !== null && _super.apply(this, arguments) || this;
  8402. _this._duplicateId = 0;
  8403. return _this;
  8404. }
  8405. SmartArrayNoDuplicate.prototype.push = function (value) {
  8406. _super.prototype.push.call(this, value);
  8407. if (!value.__smartArrayFlags) {
  8408. value.__smartArrayFlags = {};
  8409. }
  8410. value.__smartArrayFlags[this._id] = this._duplicateId;
  8411. };
  8412. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8413. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8414. return false;
  8415. }
  8416. this.push(value);
  8417. return true;
  8418. };
  8419. SmartArrayNoDuplicate.prototype.reset = function () {
  8420. _super.prototype.reset.call(this);
  8421. this._duplicateId++;
  8422. };
  8423. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8424. if (array.length === 0) {
  8425. return;
  8426. }
  8427. if (this.length + array.length > this.data.length) {
  8428. this.data.length = (this.length + array.length) * 2;
  8429. }
  8430. for (var index = 0; index < array.length; index++) {
  8431. var item = (array.data || array)[index];
  8432. this.pushNoDuplicate(item);
  8433. }
  8434. };
  8435. return SmartArrayNoDuplicate;
  8436. }(SmartArray));
  8437. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8438. })(BABYLON || (BABYLON = {}));
  8439. //# sourceMappingURL=babylon.smartArray.js.map
  8440. var BABYLON;
  8441. (function (BABYLON) {
  8442. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8443. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8444. var LoadFileError = /** @class */ (function (_super) {
  8445. __extends(LoadFileError, _super);
  8446. function LoadFileError(message, request) {
  8447. var _this = _super.call(this, message) || this;
  8448. _this.request = request;
  8449. _this.name = "LoadFileError";
  8450. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8451. return _this;
  8452. }
  8453. // Polyfill for Object.setPrototypeOf if necessary.
  8454. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8455. return LoadFileError;
  8456. }(Error));
  8457. BABYLON.LoadFileError = LoadFileError;
  8458. var RetryStrategy = /** @class */ (function () {
  8459. function RetryStrategy() {
  8460. }
  8461. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8462. if (maxRetries === void 0) { maxRetries = 3; }
  8463. if (baseInterval === void 0) { baseInterval = 500; }
  8464. return function (url, request, retryIndex) {
  8465. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8466. return -1;
  8467. }
  8468. return Math.pow(2, retryIndex) * baseInterval;
  8469. };
  8470. };
  8471. return RetryStrategy;
  8472. }());
  8473. BABYLON.RetryStrategy = RetryStrategy;
  8474. // Screenshots
  8475. var screenshotCanvas;
  8476. var cloneValue = function (source, destinationObject) {
  8477. if (!source)
  8478. return null;
  8479. if (source instanceof BABYLON.Mesh) {
  8480. return null;
  8481. }
  8482. if (source instanceof BABYLON.SubMesh) {
  8483. return source.clone(destinationObject);
  8484. }
  8485. else if (source.clone) {
  8486. return source.clone();
  8487. }
  8488. return null;
  8489. };
  8490. var Tools = /** @class */ (function () {
  8491. function Tools() {
  8492. }
  8493. /**
  8494. * Interpolates between a and b via alpha
  8495. * @param a The lower value (returned when alpha = 0)
  8496. * @param b The upper value (returned when alpha = 1)
  8497. * @param alpha The interpolation-factor
  8498. * @return The mixed value
  8499. */
  8500. Tools.Mix = function (a, b, alpha) {
  8501. return a * (1 - alpha) + b * alpha;
  8502. };
  8503. Tools.Instantiate = function (className) {
  8504. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8505. return Tools.RegisteredExternalClasses[className];
  8506. }
  8507. var arr = className.split(".");
  8508. var fn = (window || this);
  8509. for (var i = 0, len = arr.length; i < len; i++) {
  8510. fn = fn[arr[i]];
  8511. }
  8512. if (typeof fn !== "function") {
  8513. return null;
  8514. }
  8515. return fn;
  8516. };
  8517. /**
  8518. * Provides a slice function that will work even on IE
  8519. * @param data defines the array to slice
  8520. * @param start defines the start of the data (optional)
  8521. * @param end defines the end of the data (optional)
  8522. * @returns the new sliced array
  8523. */
  8524. Tools.Slice = function (data, start, end) {
  8525. if (data.slice) {
  8526. return data.slice(start, end);
  8527. }
  8528. return Array.prototype.slice.call(data, start, end);
  8529. };
  8530. Tools.SetImmediate = function (action) {
  8531. if (window.setImmediate) {
  8532. window.setImmediate(action);
  8533. }
  8534. else {
  8535. setTimeout(action, 1);
  8536. }
  8537. };
  8538. Tools.IsExponentOfTwo = function (value) {
  8539. var count = 1;
  8540. do {
  8541. count *= 2;
  8542. } while (count < value);
  8543. return count === value;
  8544. };
  8545. /**
  8546. * Returns the nearest 32-bit single precision float representation of a Number
  8547. * @param value A Number. If the parameter is of a different type, it will get converted
  8548. * to a number or to NaN if it cannot be converted
  8549. * @returns number
  8550. */
  8551. Tools.FloatRound = function (value) {
  8552. if (Math.fround) {
  8553. return Math.fround(value);
  8554. }
  8555. return (Tools._tmpFloatArray[0] = value);
  8556. };
  8557. /**
  8558. * Find the next highest power of two.
  8559. * @param x Number to start search from.
  8560. * @return Next highest power of two.
  8561. */
  8562. Tools.CeilingPOT = function (x) {
  8563. x--;
  8564. x |= x >> 1;
  8565. x |= x >> 2;
  8566. x |= x >> 4;
  8567. x |= x >> 8;
  8568. x |= x >> 16;
  8569. x++;
  8570. return x;
  8571. };
  8572. /**
  8573. * Find the next lowest power of two.
  8574. * @param x Number to start search from.
  8575. * @return Next lowest power of two.
  8576. */
  8577. Tools.FloorPOT = function (x) {
  8578. x = x | (x >> 1);
  8579. x = x | (x >> 2);
  8580. x = x | (x >> 4);
  8581. x = x | (x >> 8);
  8582. x = x | (x >> 16);
  8583. return x - (x >> 1);
  8584. };
  8585. /**
  8586. * Find the nearest power of two.
  8587. * @param x Number to start search from.
  8588. * @return Next nearest power of two.
  8589. */
  8590. Tools.NearestPOT = function (x) {
  8591. var c = Tools.CeilingPOT(x);
  8592. var f = Tools.FloorPOT(x);
  8593. return (c - x) > (x - f) ? f : c;
  8594. };
  8595. Tools.GetExponentOfTwo = function (value, max, mode) {
  8596. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8597. var pot;
  8598. switch (mode) {
  8599. case BABYLON.Engine.SCALEMODE_FLOOR:
  8600. pot = Tools.FloorPOT(value);
  8601. break;
  8602. case BABYLON.Engine.SCALEMODE_NEAREST:
  8603. pot = Tools.NearestPOT(value);
  8604. break;
  8605. case BABYLON.Engine.SCALEMODE_CEILING:
  8606. default:
  8607. pot = Tools.CeilingPOT(value);
  8608. break;
  8609. }
  8610. return Math.min(pot, max);
  8611. };
  8612. Tools.GetFilename = function (path) {
  8613. var index = path.lastIndexOf("/");
  8614. if (index < 0)
  8615. return path;
  8616. return path.substring(index + 1);
  8617. };
  8618. /**
  8619. * Extracts the "folder" part of a path (everything before the filename).
  8620. * @param uri The URI to extract the info from
  8621. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8622. * @returns The "folder" part of the path
  8623. */
  8624. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8625. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8626. var index = uri.lastIndexOf("/");
  8627. if (index < 0) {
  8628. if (returnUnchangedIfNoSlash) {
  8629. return uri;
  8630. }
  8631. return "";
  8632. }
  8633. return uri.substring(0, index + 1);
  8634. };
  8635. Tools.GetDOMTextContent = function (element) {
  8636. var result = "";
  8637. var child = element.firstChild;
  8638. while (child) {
  8639. if (child.nodeType === 3) {
  8640. result += child.textContent;
  8641. }
  8642. child = child.nextSibling;
  8643. }
  8644. return result;
  8645. };
  8646. Tools.ToDegrees = function (angle) {
  8647. return angle * 180 / Math.PI;
  8648. };
  8649. Tools.ToRadians = function (angle) {
  8650. return angle * Math.PI / 180;
  8651. };
  8652. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8653. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8654. var output = "";
  8655. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8656. var i = 0;
  8657. var bytes = new Uint8Array(buffer);
  8658. while (i < bytes.length) {
  8659. chr1 = bytes[i++];
  8660. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8661. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8662. enc1 = chr1 >> 2;
  8663. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8664. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8665. enc4 = chr3 & 63;
  8666. if (isNaN(chr2)) {
  8667. enc3 = enc4 = 64;
  8668. }
  8669. else if (isNaN(chr3)) {
  8670. enc4 = 64;
  8671. }
  8672. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8673. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8674. }
  8675. return "data:image/png;base64," + output;
  8676. };
  8677. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8678. if (bias === void 0) { bias = null; }
  8679. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8680. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8681. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8682. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8683. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8684. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8685. }
  8686. if (bias) {
  8687. minimum.x -= minimum.x * bias.x + bias.y;
  8688. minimum.y -= minimum.y * bias.x + bias.y;
  8689. minimum.z -= minimum.z * bias.x + bias.y;
  8690. maximum.x += maximum.x * bias.x + bias.y;
  8691. maximum.y += maximum.y * bias.x + bias.y;
  8692. maximum.z += maximum.z * bias.x + bias.y;
  8693. }
  8694. return {
  8695. minimum: minimum,
  8696. maximum: maximum
  8697. };
  8698. };
  8699. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8700. if (bias === void 0) { bias = null; }
  8701. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8702. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8703. if (!stride) {
  8704. stride = 3;
  8705. }
  8706. for (var index = start; index < start + count; index++) {
  8707. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8708. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8709. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8710. }
  8711. if (bias) {
  8712. minimum.x -= minimum.x * bias.x + bias.y;
  8713. minimum.y -= minimum.y * bias.x + bias.y;
  8714. minimum.z -= minimum.z * bias.x + bias.y;
  8715. maximum.x += maximum.x * bias.x + bias.y;
  8716. maximum.y += maximum.y * bias.x + bias.y;
  8717. maximum.z += maximum.z * bias.x + bias.y;
  8718. }
  8719. return {
  8720. minimum: minimum,
  8721. maximum: maximum
  8722. };
  8723. };
  8724. Tools.Vector2ArrayFeeder = function (array) {
  8725. return function (index) {
  8726. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8727. var length = isFloatArray ? array.length / 2 : array.length;
  8728. if (index >= length) {
  8729. return null;
  8730. }
  8731. if (isFloatArray) {
  8732. var fa = array;
  8733. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8734. }
  8735. var a = array;
  8736. return a[index];
  8737. };
  8738. };
  8739. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8740. if (bias === void 0) { bias = null; }
  8741. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8742. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8743. var i = 0;
  8744. var cur = feeder(i++);
  8745. while (cur) {
  8746. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8747. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8748. cur = feeder(i++);
  8749. }
  8750. if (bias) {
  8751. minimum.x -= minimum.x * bias.x + bias.y;
  8752. minimum.y -= minimum.y * bias.x + bias.y;
  8753. maximum.x += maximum.x * bias.x + bias.y;
  8754. maximum.y += maximum.y * bias.x + bias.y;
  8755. }
  8756. return {
  8757. minimum: minimum,
  8758. maximum: maximum
  8759. };
  8760. };
  8761. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8762. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8763. return null;
  8764. return Array.isArray(obj) ? obj : [obj];
  8765. };
  8766. // Misc.
  8767. Tools.GetPointerPrefix = function () {
  8768. var eventPrefix = "pointer";
  8769. // Check if pointer events are supported
  8770. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8771. eventPrefix = "mouse";
  8772. }
  8773. return eventPrefix;
  8774. };
  8775. /**
  8776. * @param func - the function to be called
  8777. * @param requester - the object that will request the next frame. Falls back to window.
  8778. */
  8779. Tools.QueueNewFrame = function (func, requester) {
  8780. if (!Tools.IsWindowObjectExist()) {
  8781. return setTimeout(func, 16);
  8782. }
  8783. if (!requester) {
  8784. requester = window;
  8785. }
  8786. if (requester.requestAnimationFrame) {
  8787. return requester.requestAnimationFrame(func);
  8788. }
  8789. else if (requester.msRequestAnimationFrame) {
  8790. return requester.msRequestAnimationFrame(func);
  8791. }
  8792. else if (requester.webkitRequestAnimationFrame) {
  8793. return requester.webkitRequestAnimationFrame(func);
  8794. }
  8795. else if (requester.mozRequestAnimationFrame) {
  8796. return requester.mozRequestAnimationFrame(func);
  8797. }
  8798. else if (requester.oRequestAnimationFrame) {
  8799. return requester.oRequestAnimationFrame(func);
  8800. }
  8801. else {
  8802. return window.setTimeout(func, 16);
  8803. }
  8804. };
  8805. Tools.RequestFullscreen = function (element) {
  8806. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8807. if (!requestFunction)
  8808. return;
  8809. requestFunction.call(element);
  8810. };
  8811. Tools.ExitFullscreen = function () {
  8812. if (document.exitFullscreen) {
  8813. document.exitFullscreen();
  8814. }
  8815. else if (document.mozCancelFullScreen) {
  8816. document.mozCancelFullScreen();
  8817. }
  8818. else if (document.webkitCancelFullScreen) {
  8819. document.webkitCancelFullScreen();
  8820. }
  8821. else if (document.msCancelFullScreen) {
  8822. document.msCancelFullScreen();
  8823. }
  8824. };
  8825. Tools.SetCorsBehavior = function (url, element) {
  8826. if (url && url.indexOf("data:") === 0) {
  8827. return;
  8828. }
  8829. if (Tools.CorsBehavior) {
  8830. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8831. element.crossOrigin = Tools.CorsBehavior;
  8832. }
  8833. else {
  8834. var result = Tools.CorsBehavior(url);
  8835. if (result) {
  8836. element.crossOrigin = result;
  8837. }
  8838. }
  8839. }
  8840. };
  8841. // External files
  8842. Tools.CleanUrl = function (url) {
  8843. url = url.replace(/#/mg, "%23");
  8844. return url;
  8845. };
  8846. Tools.LoadImage = function (url, onLoad, onError, database) {
  8847. if (url instanceof ArrayBuffer) {
  8848. url = Tools.EncodeArrayBufferTobase64(url);
  8849. }
  8850. url = Tools.CleanUrl(url);
  8851. url = Tools.PreprocessUrl(url);
  8852. var img = new Image();
  8853. Tools.SetCorsBehavior(url, img);
  8854. var loadHandler = function () {
  8855. img.removeEventListener("load", loadHandler);
  8856. img.removeEventListener("error", errorHandler);
  8857. onLoad(img);
  8858. };
  8859. var errorHandler = function (err) {
  8860. img.removeEventListener("load", loadHandler);
  8861. img.removeEventListener("error", errorHandler);
  8862. Tools.Error("Error while trying to load image: " + url);
  8863. if (onError) {
  8864. onError("Error while trying to load image: " + url, err);
  8865. }
  8866. };
  8867. img.addEventListener("load", loadHandler);
  8868. img.addEventListener("error", errorHandler);
  8869. var noIndexedDB = function () {
  8870. img.src = url;
  8871. };
  8872. var loadFromIndexedDB = function () {
  8873. if (database) {
  8874. database.loadImageFromDB(url, img);
  8875. }
  8876. };
  8877. //ANY database to do!
  8878. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8879. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8880. }
  8881. else {
  8882. if (url.indexOf("file:") !== -1) {
  8883. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8884. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8885. try {
  8886. var blobURL;
  8887. try {
  8888. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8889. }
  8890. catch (ex) {
  8891. // Chrome doesn't support oneTimeOnly parameter
  8892. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8893. }
  8894. img.src = blobURL;
  8895. }
  8896. catch (e) {
  8897. img.src = "";
  8898. }
  8899. return img;
  8900. }
  8901. }
  8902. noIndexedDB();
  8903. }
  8904. return img;
  8905. };
  8906. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8907. url = Tools.CleanUrl(url);
  8908. url = Tools.PreprocessUrl(url);
  8909. // If file and file input are set
  8910. if (url.indexOf("file:") !== -1) {
  8911. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8912. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8913. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8914. }
  8915. }
  8916. var loadUrl = Tools.BaseUrl + url;
  8917. var aborted = false;
  8918. var fileRequest = {
  8919. onCompleteObservable: new BABYLON.Observable(),
  8920. abort: function () { return aborted = true; },
  8921. };
  8922. var requestFile = function () {
  8923. var request = new XMLHttpRequest();
  8924. var retryHandle = null;
  8925. fileRequest.abort = function () {
  8926. aborted = true;
  8927. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8928. request.abort();
  8929. }
  8930. if (retryHandle !== null) {
  8931. clearTimeout(retryHandle);
  8932. retryHandle = null;
  8933. }
  8934. };
  8935. var retryLoop = function (retryIndex) {
  8936. request.open('GET', loadUrl, true);
  8937. if (useArrayBuffer) {
  8938. request.responseType = "arraybuffer";
  8939. }
  8940. if (onProgress) {
  8941. request.addEventListener("progress", onProgress);
  8942. }
  8943. var onLoadEnd = function () {
  8944. request.removeEventListener("loadend", onLoadEnd);
  8945. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8946. fileRequest.onCompleteObservable.clear();
  8947. };
  8948. request.addEventListener("loadend", onLoadEnd);
  8949. var onReadyStateChange = function () {
  8950. if (aborted) {
  8951. return;
  8952. }
  8953. // In case of undefined state in some browsers.
  8954. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8955. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8956. request.removeEventListener("readystatechange", onReadyStateChange);
  8957. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8958. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8959. return;
  8960. }
  8961. var retryStrategy = Tools.DefaultRetryStrategy;
  8962. if (retryStrategy) {
  8963. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8964. if (waitTime !== -1) {
  8965. // Prevent the request from completing for retry.
  8966. request.removeEventListener("loadend", onLoadEnd);
  8967. request = new XMLHttpRequest();
  8968. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8969. return;
  8970. }
  8971. }
  8972. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8973. if (onError) {
  8974. onError(request, e);
  8975. }
  8976. else {
  8977. throw e;
  8978. }
  8979. }
  8980. };
  8981. request.addEventListener("readystatechange", onReadyStateChange);
  8982. request.send();
  8983. };
  8984. retryLoop(0);
  8985. };
  8986. // Caching all files
  8987. if (database && database.enableSceneOffline) {
  8988. var noIndexedDB_1 = function () {
  8989. if (!aborted) {
  8990. requestFile();
  8991. }
  8992. };
  8993. var loadFromIndexedDB = function () {
  8994. // TODO: database needs to support aborting and should return a IFileRequest
  8995. if (aborted) {
  8996. return;
  8997. }
  8998. if (database) {
  8999. database.loadFileFromDB(url, function (data) {
  9000. if (!aborted) {
  9001. onSuccess(data);
  9002. }
  9003. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9004. }, onProgress ? function (event) {
  9005. if (!aborted) {
  9006. onProgress(event);
  9007. }
  9008. } : undefined, noIndexedDB_1, useArrayBuffer);
  9009. }
  9010. };
  9011. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9012. }
  9013. else {
  9014. requestFile();
  9015. }
  9016. return fileRequest;
  9017. };
  9018. /**
  9019. * Load a script (identified by an url). When the url returns, the
  9020. * content of this file is added into a new script element, attached to the DOM (body element)
  9021. */
  9022. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9023. var head = document.getElementsByTagName('head')[0];
  9024. var script = document.createElement('script');
  9025. script.type = 'text/javascript';
  9026. script.src = scriptUrl;
  9027. script.onload = function () {
  9028. if (onSuccess) {
  9029. onSuccess();
  9030. }
  9031. };
  9032. script.onerror = function (e) {
  9033. if (onError) {
  9034. onError("Unable to load script '" + scriptUrl + "'", e);
  9035. }
  9036. };
  9037. head.appendChild(script);
  9038. };
  9039. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9040. var reader = new FileReader();
  9041. var request = {
  9042. onCompleteObservable: new BABYLON.Observable(),
  9043. abort: function () { return reader.abort(); },
  9044. };
  9045. reader.onloadend = function (e) {
  9046. request.onCompleteObservable.notifyObservers(request);
  9047. };
  9048. reader.onload = function (e) {
  9049. //target doesn't have result from ts 1.3
  9050. callback(e.target['result']);
  9051. };
  9052. reader.onprogress = progressCallback;
  9053. reader.readAsDataURL(fileToLoad);
  9054. return request;
  9055. };
  9056. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9057. var reader = new FileReader();
  9058. var request = {
  9059. onCompleteObservable: new BABYLON.Observable(),
  9060. abort: function () { return reader.abort(); },
  9061. };
  9062. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9063. reader.onerror = function (e) {
  9064. Tools.Log("Error while reading file: " + fileToLoad.name);
  9065. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9066. };
  9067. reader.onload = function (e) {
  9068. //target doesn't have result from ts 1.3
  9069. callback(e.target['result']);
  9070. };
  9071. if (progressCallBack) {
  9072. reader.onprogress = progressCallBack;
  9073. }
  9074. if (!useArrayBuffer) {
  9075. // Asynchronous read
  9076. reader.readAsText(fileToLoad);
  9077. }
  9078. else {
  9079. reader.readAsArrayBuffer(fileToLoad);
  9080. }
  9081. return request;
  9082. };
  9083. //returns a downloadable url to a file content.
  9084. Tools.FileAsURL = function (content) {
  9085. var fileBlob = new Blob([content]);
  9086. var url = window.URL || window.webkitURL;
  9087. var link = url.createObjectURL(fileBlob);
  9088. return link;
  9089. };
  9090. // Misc.
  9091. Tools.Format = function (value, decimals) {
  9092. if (decimals === void 0) { decimals = 2; }
  9093. return value.toFixed(decimals);
  9094. };
  9095. Tools.CheckExtends = function (v, min, max) {
  9096. if (v.x < min.x)
  9097. min.x = v.x;
  9098. if (v.y < min.y)
  9099. min.y = v.y;
  9100. if (v.z < min.z)
  9101. min.z = v.z;
  9102. if (v.x > max.x)
  9103. max.x = v.x;
  9104. if (v.y > max.y)
  9105. max.y = v.y;
  9106. if (v.z > max.z)
  9107. max.z = v.z;
  9108. };
  9109. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9110. for (var prop in source) {
  9111. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9112. continue;
  9113. }
  9114. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9115. continue;
  9116. }
  9117. var sourceValue = source[prop];
  9118. var typeOfSourceValue = typeof sourceValue;
  9119. if (typeOfSourceValue === "function") {
  9120. continue;
  9121. }
  9122. try {
  9123. if (typeOfSourceValue === "object") {
  9124. if (sourceValue instanceof Array) {
  9125. destination[prop] = [];
  9126. if (sourceValue.length > 0) {
  9127. if (typeof sourceValue[0] == "object") {
  9128. for (var index = 0; index < sourceValue.length; index++) {
  9129. var clonedValue = cloneValue(sourceValue[index], destination);
  9130. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9131. destination[prop].push(clonedValue);
  9132. }
  9133. }
  9134. }
  9135. else {
  9136. destination[prop] = sourceValue.slice(0);
  9137. }
  9138. }
  9139. }
  9140. else {
  9141. destination[prop] = cloneValue(sourceValue, destination);
  9142. }
  9143. }
  9144. else {
  9145. destination[prop] = sourceValue;
  9146. }
  9147. }
  9148. catch (e) {
  9149. // Just ignore error (it could be because of a read-only property)
  9150. }
  9151. }
  9152. };
  9153. Tools.IsEmpty = function (obj) {
  9154. for (var i in obj) {
  9155. if (obj.hasOwnProperty(i)) {
  9156. return false;
  9157. }
  9158. }
  9159. return true;
  9160. };
  9161. Tools.RegisterTopRootEvents = function (events) {
  9162. for (var index = 0; index < events.length; index++) {
  9163. var event = events[index];
  9164. window.addEventListener(event.name, event.handler, false);
  9165. try {
  9166. if (window.parent) {
  9167. window.parent.addEventListener(event.name, event.handler, false);
  9168. }
  9169. }
  9170. catch (e) {
  9171. // Silently fails...
  9172. }
  9173. }
  9174. };
  9175. Tools.UnregisterTopRootEvents = function (events) {
  9176. for (var index = 0; index < events.length; index++) {
  9177. var event = events[index];
  9178. window.removeEventListener(event.name, event.handler);
  9179. try {
  9180. if (window.parent) {
  9181. window.parent.removeEventListener(event.name, event.handler);
  9182. }
  9183. }
  9184. catch (e) {
  9185. // Silently fails...
  9186. }
  9187. }
  9188. };
  9189. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9190. if (mimeType === void 0) { mimeType = "image/png"; }
  9191. // Read the contents of the framebuffer
  9192. var numberOfChannelsByLine = width * 4;
  9193. var halfHeight = height / 2;
  9194. //Reading datas from WebGL
  9195. var data = engine.readPixels(0, 0, width, height);
  9196. //To flip image on Y axis.
  9197. for (var i = 0; i < halfHeight; i++) {
  9198. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9199. var currentCell = j + i * numberOfChannelsByLine;
  9200. var targetLine = height - i - 1;
  9201. var targetCell = j + targetLine * numberOfChannelsByLine;
  9202. var temp = data[currentCell];
  9203. data[currentCell] = data[targetCell];
  9204. data[targetCell] = temp;
  9205. }
  9206. }
  9207. // Create a 2D canvas to store the result
  9208. if (!screenshotCanvas) {
  9209. screenshotCanvas = document.createElement('canvas');
  9210. }
  9211. screenshotCanvas.width = width;
  9212. screenshotCanvas.height = height;
  9213. var context = screenshotCanvas.getContext('2d');
  9214. if (context) {
  9215. // Copy the pixels to a 2D canvas
  9216. var imageData = context.createImageData(width, height);
  9217. var castData = (imageData.data);
  9218. castData.set(data);
  9219. context.putImageData(imageData, 0, 0);
  9220. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9221. }
  9222. };
  9223. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9224. if (mimeType === void 0) { mimeType = "image/png"; }
  9225. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9226. if (successCallback) {
  9227. successCallback(base64Image);
  9228. }
  9229. else {
  9230. // We need HTMLCanvasElement.toBlob for HD screenshots
  9231. if (!screenshotCanvas.toBlob) {
  9232. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9233. screenshotCanvas.toBlob = function (callback, type, quality) {
  9234. var _this = this;
  9235. setTimeout(function () {
  9236. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9237. for (var i = 0; i < len; i++) {
  9238. arr[i] = binStr.charCodeAt(i);
  9239. }
  9240. callback(new Blob([arr], { type: type || 'image/png' }));
  9241. });
  9242. };
  9243. }
  9244. screenshotCanvas.toBlob(function (blob) {
  9245. var url = URL.createObjectURL(blob);
  9246. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9247. if (("download" in document.createElement("a"))) {
  9248. var a = window.document.createElement("a");
  9249. a.href = url;
  9250. if (fileName) {
  9251. a.setAttribute("download", fileName);
  9252. }
  9253. else {
  9254. var date = new Date();
  9255. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9256. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9257. }
  9258. window.document.body.appendChild(a);
  9259. a.addEventListener("click", function () {
  9260. if (a.parentElement) {
  9261. a.parentElement.removeChild(a);
  9262. }
  9263. });
  9264. a.click();
  9265. }
  9266. else {
  9267. var newWindow = window.open("");
  9268. if (!newWindow)
  9269. return;
  9270. var img = newWindow.document.createElement("img");
  9271. img.onload = function () {
  9272. // no longer need to read the blob so it's revoked
  9273. URL.revokeObjectURL(url);
  9274. };
  9275. img.src = url;
  9276. newWindow.document.body.appendChild(img);
  9277. }
  9278. });
  9279. }
  9280. };
  9281. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9282. if (mimeType === void 0) { mimeType = "image/png"; }
  9283. var width;
  9284. var height;
  9285. // If a precision value is specified
  9286. if (size.precision) {
  9287. width = Math.round(engine.getRenderWidth() * size.precision);
  9288. height = Math.round(width / engine.getAspectRatio(camera));
  9289. }
  9290. else if (size.width && size.height) {
  9291. width = size.width;
  9292. height = size.height;
  9293. }
  9294. //If passing only width, computing height to keep display canvas ratio.
  9295. else if (size.width && !size.height) {
  9296. width = size.width;
  9297. height = Math.round(width / engine.getAspectRatio(camera));
  9298. }
  9299. //If passing only height, computing width to keep display canvas ratio.
  9300. else if (size.height && !size.width) {
  9301. height = size.height;
  9302. width = Math.round(height * engine.getAspectRatio(camera));
  9303. }
  9304. //Assuming here that "size" parameter is a number
  9305. else if (!isNaN(size)) {
  9306. height = size;
  9307. width = size;
  9308. }
  9309. else {
  9310. Tools.Error("Invalid 'size' parameter !");
  9311. return;
  9312. }
  9313. if (!screenshotCanvas) {
  9314. screenshotCanvas = document.createElement('canvas');
  9315. }
  9316. screenshotCanvas.width = width;
  9317. screenshotCanvas.height = height;
  9318. var renderContext = screenshotCanvas.getContext("2d");
  9319. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9320. var newWidth = width;
  9321. var newHeight = newWidth / ratio;
  9322. if (newHeight > height) {
  9323. newHeight = height;
  9324. newWidth = newHeight * ratio;
  9325. }
  9326. var offsetX = Math.max(0, width - newWidth) / 2;
  9327. var offsetY = Math.max(0, height - newHeight) / 2;
  9328. var renderingCanvas = engine.getRenderingCanvas();
  9329. if (renderContext && renderingCanvas) {
  9330. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9331. }
  9332. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9333. };
  9334. /**
  9335. * Generates an image screenshot from the specified camera.
  9336. *
  9337. * @param engine The engine to use for rendering
  9338. * @param camera The camera to use for rendering
  9339. * @param size This parameter can be set to a single number or to an object with the
  9340. * following (optional) properties: precision, width, height. If a single number is passed,
  9341. * it will be used for both width and height. If an object is passed, the screenshot size
  9342. * will be derived from the parameters. The precision property is a multiplier allowing
  9343. * rendering at a higher or lower resolution.
  9344. * @param successCallback The callback receives a single parameter which contains the
  9345. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9346. * src parameter of an <img> to display it.
  9347. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9348. * Check your browser for supported MIME types.
  9349. * @param samples Texture samples (default: 1)
  9350. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9351. * @param fileName A name for for the downloaded file.
  9352. * @constructor
  9353. */
  9354. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9355. if (mimeType === void 0) { mimeType = "image/png"; }
  9356. if (samples === void 0) { samples = 1; }
  9357. if (antialiasing === void 0) { antialiasing = false; }
  9358. var width;
  9359. var height;
  9360. //If a precision value is specified
  9361. if (size.precision) {
  9362. width = Math.round(engine.getRenderWidth() * size.precision);
  9363. height = Math.round(width / engine.getAspectRatio(camera));
  9364. size = { width: width, height: height };
  9365. }
  9366. else if (size.width && size.height) {
  9367. width = size.width;
  9368. height = size.height;
  9369. }
  9370. //If passing only width, computing height to keep display canvas ratio.
  9371. else if (size.width && !size.height) {
  9372. width = size.width;
  9373. height = Math.round(width / engine.getAspectRatio(camera));
  9374. size = { width: width, height: height };
  9375. }
  9376. //If passing only height, computing width to keep display canvas ratio.
  9377. else if (size.height && !size.width) {
  9378. height = size.height;
  9379. width = Math.round(height * engine.getAspectRatio(camera));
  9380. size = { width: width, height: height };
  9381. }
  9382. //Assuming here that "size" parameter is a number
  9383. else if (!isNaN(size)) {
  9384. height = size;
  9385. width = size;
  9386. }
  9387. else {
  9388. Tools.Error("Invalid 'size' parameter !");
  9389. return;
  9390. }
  9391. var scene = camera.getScene();
  9392. var previousCamera = null;
  9393. if (scene.activeCamera !== camera) {
  9394. previousCamera = scene.activeCamera;
  9395. scene.activeCamera = camera;
  9396. }
  9397. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9398. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9399. texture.renderList = null;
  9400. texture.samples = samples;
  9401. if (antialiasing) {
  9402. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9403. }
  9404. texture.onAfterRenderObservable.add(function () {
  9405. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9406. });
  9407. scene.incrementRenderId();
  9408. scene.resetCachedMaterial();
  9409. texture.render(true);
  9410. texture.dispose();
  9411. if (previousCamera) {
  9412. scene.activeCamera = previousCamera;
  9413. }
  9414. camera.getProjectionMatrix(true); // Force cache refresh;
  9415. };
  9416. // XHR response validator for local file scenario
  9417. Tools.ValidateXHRData = function (xhr, dataType) {
  9418. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9419. if (dataType === void 0) { dataType = 7; }
  9420. try {
  9421. if (dataType & 1) {
  9422. if (xhr.responseText && xhr.responseText.length > 0) {
  9423. return true;
  9424. }
  9425. else if (dataType === 1) {
  9426. return false;
  9427. }
  9428. }
  9429. if (dataType & 2) {
  9430. // Check header width and height since there is no "TGA" magic number
  9431. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9432. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9433. return true;
  9434. }
  9435. else if (dataType === 2) {
  9436. return false;
  9437. }
  9438. }
  9439. if (dataType & 4) {
  9440. // Check for the "DDS" magic number
  9441. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9442. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9443. return true;
  9444. }
  9445. else {
  9446. return false;
  9447. }
  9448. }
  9449. }
  9450. catch (e) {
  9451. // Global protection
  9452. }
  9453. return false;
  9454. };
  9455. /**
  9456. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9457. * Be aware Math.random() could cause collisions, but:
  9458. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9459. */
  9460. Tools.RandomId = function () {
  9461. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9462. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9463. return v.toString(16);
  9464. });
  9465. };
  9466. /**
  9467. * Test if the given uri is a base64 string.
  9468. * @param uri The uri to test
  9469. * @return True if the uri is a base64 string or false otherwise.
  9470. */
  9471. Tools.IsBase64 = function (uri) {
  9472. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9473. };
  9474. /**
  9475. * Decode the given base64 uri.
  9476. * @param uri The uri to decode
  9477. * @return The decoded base64 data.
  9478. */
  9479. Tools.DecodeBase64 = function (uri) {
  9480. var decodedString = atob(uri.split(",")[1]);
  9481. var bufferLength = decodedString.length;
  9482. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9483. for (var i = 0; i < bufferLength; i++) {
  9484. bufferView[i] = decodedString.charCodeAt(i);
  9485. }
  9486. return bufferView.buffer;
  9487. };
  9488. Object.defineProperty(Tools, "NoneLogLevel", {
  9489. get: function () {
  9490. return Tools._NoneLogLevel;
  9491. },
  9492. enumerable: true,
  9493. configurable: true
  9494. });
  9495. Object.defineProperty(Tools, "MessageLogLevel", {
  9496. get: function () {
  9497. return Tools._MessageLogLevel;
  9498. },
  9499. enumerable: true,
  9500. configurable: true
  9501. });
  9502. Object.defineProperty(Tools, "WarningLogLevel", {
  9503. get: function () {
  9504. return Tools._WarningLogLevel;
  9505. },
  9506. enumerable: true,
  9507. configurable: true
  9508. });
  9509. Object.defineProperty(Tools, "ErrorLogLevel", {
  9510. get: function () {
  9511. return Tools._ErrorLogLevel;
  9512. },
  9513. enumerable: true,
  9514. configurable: true
  9515. });
  9516. Object.defineProperty(Tools, "AllLogLevel", {
  9517. get: function () {
  9518. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9519. },
  9520. enumerable: true,
  9521. configurable: true
  9522. });
  9523. Tools._AddLogEntry = function (entry) {
  9524. Tools._LogCache = entry + Tools._LogCache;
  9525. if (Tools.OnNewCacheEntry) {
  9526. Tools.OnNewCacheEntry(entry);
  9527. }
  9528. };
  9529. Tools._FormatMessage = function (message) {
  9530. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9531. var date = new Date();
  9532. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9533. };
  9534. Tools._LogDisabled = function (message) {
  9535. // nothing to do
  9536. };
  9537. Tools._LogEnabled = function (message) {
  9538. var formattedMessage = Tools._FormatMessage(message);
  9539. console.log("BJS - " + formattedMessage);
  9540. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9541. Tools._AddLogEntry(entry);
  9542. };
  9543. Tools._WarnDisabled = function (message) {
  9544. // nothing to do
  9545. };
  9546. Tools._WarnEnabled = function (message) {
  9547. var formattedMessage = Tools._FormatMessage(message);
  9548. console.warn("BJS - " + formattedMessage);
  9549. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9550. Tools._AddLogEntry(entry);
  9551. };
  9552. Tools._ErrorDisabled = function (message) {
  9553. // nothing to do
  9554. };
  9555. Tools._ErrorEnabled = function (message) {
  9556. Tools.errorsCount++;
  9557. var formattedMessage = Tools._FormatMessage(message);
  9558. console.error("BJS - " + formattedMessage);
  9559. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9560. Tools._AddLogEntry(entry);
  9561. };
  9562. Object.defineProperty(Tools, "LogCache", {
  9563. get: function () {
  9564. return Tools._LogCache;
  9565. },
  9566. enumerable: true,
  9567. configurable: true
  9568. });
  9569. Tools.ClearLogCache = function () {
  9570. Tools._LogCache = "";
  9571. Tools.errorsCount = 0;
  9572. };
  9573. Object.defineProperty(Tools, "LogLevels", {
  9574. set: function (level) {
  9575. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9576. Tools.Log = Tools._LogEnabled;
  9577. }
  9578. else {
  9579. Tools.Log = Tools._LogDisabled;
  9580. }
  9581. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9582. Tools.Warn = Tools._WarnEnabled;
  9583. }
  9584. else {
  9585. Tools.Warn = Tools._WarnDisabled;
  9586. }
  9587. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9588. Tools.Error = Tools._ErrorEnabled;
  9589. }
  9590. else {
  9591. Tools.Error = Tools._ErrorDisabled;
  9592. }
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Tools.IsWindowObjectExist = function () {
  9598. return (typeof window) !== "undefined";
  9599. };
  9600. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9601. get: function () {
  9602. return Tools._PerformanceNoneLogLevel;
  9603. },
  9604. enumerable: true,
  9605. configurable: true
  9606. });
  9607. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9608. get: function () {
  9609. return Tools._PerformanceUserMarkLogLevel;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9615. get: function () {
  9616. return Tools._PerformanceConsoleLogLevel;
  9617. },
  9618. enumerable: true,
  9619. configurable: true
  9620. });
  9621. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9622. set: function (level) {
  9623. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9624. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9625. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9626. return;
  9627. }
  9628. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9629. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9630. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9631. return;
  9632. }
  9633. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9634. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9640. };
  9641. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9642. };
  9643. Tools._StartUserMark = function (counterName, condition) {
  9644. if (condition === void 0) { condition = true; }
  9645. if (!Tools._performance) {
  9646. if (!Tools.IsWindowObjectExist()) {
  9647. return;
  9648. }
  9649. Tools._performance = window.performance;
  9650. }
  9651. if (!condition || !Tools._performance.mark) {
  9652. return;
  9653. }
  9654. Tools._performance.mark(counterName + "-Begin");
  9655. };
  9656. Tools._EndUserMark = function (counterName, condition) {
  9657. if (condition === void 0) { condition = true; }
  9658. if (!condition || !Tools._performance.mark) {
  9659. return;
  9660. }
  9661. Tools._performance.mark(counterName + "-End");
  9662. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9663. };
  9664. Tools._StartPerformanceConsole = function (counterName, condition) {
  9665. if (condition === void 0) { condition = true; }
  9666. if (!condition) {
  9667. return;
  9668. }
  9669. Tools._StartUserMark(counterName, condition);
  9670. if (console.time) {
  9671. console.time(counterName);
  9672. }
  9673. };
  9674. Tools._EndPerformanceConsole = function (counterName, condition) {
  9675. if (condition === void 0) { condition = true; }
  9676. if (!condition) {
  9677. return;
  9678. }
  9679. Tools._EndUserMark(counterName, condition);
  9680. if (console.time) {
  9681. console.timeEnd(counterName);
  9682. }
  9683. };
  9684. Object.defineProperty(Tools, "Now", {
  9685. get: function () {
  9686. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9687. return window.performance.now();
  9688. }
  9689. return Date.now();
  9690. },
  9691. enumerable: true,
  9692. configurable: true
  9693. });
  9694. /**
  9695. * This method will return the name of the class used to create the instance of the given object.
  9696. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9697. * @param object the object to get the class name from
  9698. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9699. */
  9700. Tools.GetClassName = function (object, isType) {
  9701. if (isType === void 0) { isType = false; }
  9702. var name = null;
  9703. if (!isType && object.getClassName) {
  9704. name = object.getClassName();
  9705. }
  9706. else {
  9707. if (object instanceof Object) {
  9708. var classObj = isType ? object : Object.getPrototypeOf(object);
  9709. name = classObj.constructor["__bjsclassName__"];
  9710. }
  9711. if (!name) {
  9712. name = typeof object;
  9713. }
  9714. }
  9715. return name;
  9716. };
  9717. Tools.First = function (array, predicate) {
  9718. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9719. var el = array_1[_i];
  9720. if (predicate(el)) {
  9721. return el;
  9722. }
  9723. }
  9724. return null;
  9725. };
  9726. /**
  9727. * This method will return the name of the full name of the class, including its owning module (if any).
  9728. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9729. * @param object the object to get the class name from
  9730. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9731. */
  9732. Tools.getFullClassName = function (object, isType) {
  9733. if (isType === void 0) { isType = false; }
  9734. var className = null;
  9735. var moduleName = null;
  9736. if (!isType && object.getClassName) {
  9737. className = object.getClassName();
  9738. }
  9739. else {
  9740. if (object instanceof Object) {
  9741. var classObj = isType ? object : Object.getPrototypeOf(object);
  9742. className = classObj.constructor["__bjsclassName__"];
  9743. moduleName = classObj.constructor["__bjsmoduleName__"];
  9744. }
  9745. if (!className) {
  9746. className = typeof object;
  9747. }
  9748. }
  9749. if (!className) {
  9750. return null;
  9751. }
  9752. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9753. };
  9754. /**
  9755. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9756. * @param array
  9757. */
  9758. Tools.arrayOrStringFeeder = function (array) {
  9759. return function (index) {
  9760. if (index >= array.length) {
  9761. return null;
  9762. }
  9763. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9764. if (val && val.getHashCode) {
  9765. val = val.getHashCode();
  9766. }
  9767. if (typeof val === "string") {
  9768. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9769. }
  9770. return val;
  9771. };
  9772. };
  9773. /**
  9774. * Compute the hashCode of a stream of number
  9775. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9776. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9777. * @return the hash code computed
  9778. */
  9779. Tools.hashCodeFromStream = function (feeder) {
  9780. // Based from here: http://stackoverflow.com/a/7616484/802124
  9781. var hash = 0;
  9782. var index = 0;
  9783. var chr = feeder(index++);
  9784. while (chr != null) {
  9785. hash = ((hash << 5) - hash) + chr;
  9786. hash |= 0; // Convert to 32bit integer
  9787. chr = feeder(index++);
  9788. }
  9789. return hash;
  9790. };
  9791. /**
  9792. * Returns a promise that resolves after the given amount of time.
  9793. * @param delay Number of milliseconds to delay
  9794. * @returns Promise that resolves after the given amount of time
  9795. */
  9796. Tools.DelayAsync = function (delay) {
  9797. return new Promise(function (resolve) {
  9798. setTimeout(function () {
  9799. resolve();
  9800. }, delay);
  9801. });
  9802. };
  9803. Tools.BaseUrl = "";
  9804. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9805. /**
  9806. * Default behaviour for cors in the application.
  9807. * It can be a string if the expected behavior is identical in the entire app.
  9808. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9809. */
  9810. Tools.CorsBehavior = "anonymous";
  9811. Tools.UseFallbackTexture = true;
  9812. /**
  9813. * Use this object to register external classes like custom textures or material
  9814. * to allow the laoders to instantiate them
  9815. */
  9816. Tools.RegisteredExternalClasses = {};
  9817. // Used in case of a texture loading problem
  9818. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9819. Tools._tmpFloatArray = new Float32Array(1);
  9820. Tools.PreprocessUrl = function (url) {
  9821. return url;
  9822. };
  9823. // Logs
  9824. Tools._NoneLogLevel = 0;
  9825. Tools._MessageLogLevel = 1;
  9826. Tools._WarningLogLevel = 2;
  9827. Tools._ErrorLogLevel = 4;
  9828. Tools._LogCache = "";
  9829. Tools.errorsCount = 0;
  9830. Tools.Log = Tools._LogEnabled;
  9831. Tools.Warn = Tools._WarnEnabled;
  9832. Tools.Error = Tools._ErrorEnabled;
  9833. // Performances
  9834. Tools._PerformanceNoneLogLevel = 0;
  9835. Tools._PerformanceUserMarkLogLevel = 1;
  9836. Tools._PerformanceConsoleLogLevel = 2;
  9837. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9838. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9839. return Tools;
  9840. }());
  9841. BABYLON.Tools = Tools;
  9842. /**
  9843. * This class is used to track a performance counter which is number based.
  9844. * The user has access to many properties which give statistics of different nature
  9845. *
  9846. * The implementer can track two kinds of Performance Counter: time and count
  9847. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  9848. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  9849. */
  9850. var PerfCounter = /** @class */ (function () {
  9851. function PerfCounter() {
  9852. this._startMonitoringTime = 0;
  9853. this._min = 0;
  9854. this._max = 0;
  9855. this._average = 0;
  9856. this._lastSecAverage = 0;
  9857. this._current = 0;
  9858. this._totalValueCount = 0;
  9859. this._totalAccumulated = 0;
  9860. this._lastSecAccumulated = 0;
  9861. this._lastSecTime = 0;
  9862. this._lastSecValueCount = 0;
  9863. }
  9864. Object.defineProperty(PerfCounter.prototype, "min", {
  9865. /**
  9866. * Returns the smallest value ever
  9867. */
  9868. get: function () {
  9869. return this._min;
  9870. },
  9871. enumerable: true,
  9872. configurable: true
  9873. });
  9874. Object.defineProperty(PerfCounter.prototype, "max", {
  9875. /**
  9876. * Returns the biggest value ever
  9877. */
  9878. get: function () {
  9879. return this._max;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(PerfCounter.prototype, "average", {
  9885. /**
  9886. * Returns the average value since the performance counter is running
  9887. */
  9888. get: function () {
  9889. return this._average;
  9890. },
  9891. enumerable: true,
  9892. configurable: true
  9893. });
  9894. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9895. /**
  9896. * Returns the average value of the last second the counter was monitored
  9897. */
  9898. get: function () {
  9899. return this._lastSecAverage;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(PerfCounter.prototype, "current", {
  9905. /**
  9906. * Returns the current value
  9907. */
  9908. get: function () {
  9909. return this._current;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Object.defineProperty(PerfCounter.prototype, "total", {
  9915. get: function () {
  9916. return this._totalAccumulated;
  9917. },
  9918. enumerable: true,
  9919. configurable: true
  9920. });
  9921. Object.defineProperty(PerfCounter.prototype, "count", {
  9922. get: function () {
  9923. return this._totalValueCount;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. /**
  9929. * Call this method to start monitoring a new frame.
  9930. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  9931. */
  9932. PerfCounter.prototype.fetchNewFrame = function () {
  9933. this._totalValueCount++;
  9934. this._current = 0;
  9935. this._lastSecValueCount++;
  9936. };
  9937. /**
  9938. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9939. * @param newCount the count value to add to the monitored count
  9940. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  9941. */
  9942. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9943. if (!PerfCounter.Enabled) {
  9944. return;
  9945. }
  9946. this._current += newCount;
  9947. if (fetchResult) {
  9948. this._fetchResult();
  9949. }
  9950. };
  9951. /**
  9952. * Start monitoring this performance counter
  9953. */
  9954. PerfCounter.prototype.beginMonitoring = function () {
  9955. if (!PerfCounter.Enabled) {
  9956. return;
  9957. }
  9958. this._startMonitoringTime = Tools.Now;
  9959. };
  9960. /**
  9961. * Compute the time lapsed since the previous beginMonitoring() call.
  9962. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  9963. */
  9964. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9965. if (newFrame === void 0) { newFrame = true; }
  9966. if (!PerfCounter.Enabled) {
  9967. return;
  9968. }
  9969. if (newFrame) {
  9970. this.fetchNewFrame();
  9971. }
  9972. var currentTime = Tools.Now;
  9973. this._current = currentTime - this._startMonitoringTime;
  9974. if (newFrame) {
  9975. this._fetchResult();
  9976. }
  9977. };
  9978. PerfCounter.prototype._fetchResult = function () {
  9979. this._totalAccumulated += this._current;
  9980. this._lastSecAccumulated += this._current;
  9981. // Min/Max update
  9982. this._min = Math.min(this._min, this._current);
  9983. this._max = Math.max(this._max, this._current);
  9984. this._average = this._totalAccumulated / this._totalValueCount;
  9985. // Reset last sec?
  9986. var now = Tools.Now;
  9987. if ((now - this._lastSecTime) > 1000) {
  9988. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9989. this._lastSecTime = now;
  9990. this._lastSecAccumulated = 0;
  9991. this._lastSecValueCount = 0;
  9992. }
  9993. };
  9994. PerfCounter.Enabled = true;
  9995. return PerfCounter;
  9996. }());
  9997. BABYLON.PerfCounter = PerfCounter;
  9998. /**
  9999. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10000. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10001. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10002. * @param name The name of the class, case should be preserved
  10003. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10004. */
  10005. function className(name, module) {
  10006. return function (target) {
  10007. target["__bjsclassName__"] = name;
  10008. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10009. };
  10010. }
  10011. BABYLON.className = className;
  10012. /**
  10013. * An implementation of a loop for asynchronous functions.
  10014. */
  10015. var AsyncLoop = /** @class */ (function () {
  10016. /**
  10017. * Constroctor.
  10018. * @param iterations the number of iterations.
  10019. * @param _fn the function to run each iteration
  10020. * @param _successCallback the callback that will be called upon succesful execution
  10021. * @param offset starting offset.
  10022. */
  10023. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10024. if (offset === void 0) { offset = 0; }
  10025. this.iterations = iterations;
  10026. this._fn = _fn;
  10027. this._successCallback = _successCallback;
  10028. this.index = offset - 1;
  10029. this._done = false;
  10030. }
  10031. /**
  10032. * Execute the next iteration. Must be called after the last iteration was finished.
  10033. */
  10034. AsyncLoop.prototype.executeNext = function () {
  10035. if (!this._done) {
  10036. if (this.index + 1 < this.iterations) {
  10037. ++this.index;
  10038. this._fn(this);
  10039. }
  10040. else {
  10041. this.breakLoop();
  10042. }
  10043. }
  10044. };
  10045. /**
  10046. * Break the loop and run the success callback.
  10047. */
  10048. AsyncLoop.prototype.breakLoop = function () {
  10049. this._done = true;
  10050. this._successCallback();
  10051. };
  10052. /**
  10053. * Helper function
  10054. */
  10055. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10056. if (offset === void 0) { offset = 0; }
  10057. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10058. loop.executeNext();
  10059. return loop;
  10060. };
  10061. /**
  10062. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10063. * @param iterations total number of iterations
  10064. * @param syncedIterations number of synchronous iterations in each async iteration.
  10065. * @param fn the function to call each iteration.
  10066. * @param callback a success call back that will be called when iterating stops.
  10067. * @param breakFunction a break condition (optional)
  10068. * @param timeout timeout settings for the setTimeout function. default - 0.
  10069. * @constructor
  10070. */
  10071. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10072. if (timeout === void 0) { timeout = 0; }
  10073. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10074. if (breakFunction && breakFunction())
  10075. loop.breakLoop();
  10076. else {
  10077. setTimeout(function () {
  10078. for (var i = 0; i < syncedIterations; ++i) {
  10079. var iteration = (loop.index * syncedIterations) + i;
  10080. if (iteration >= iterations)
  10081. break;
  10082. fn(iteration);
  10083. if (breakFunction && breakFunction()) {
  10084. loop.breakLoop();
  10085. break;
  10086. }
  10087. }
  10088. loop.executeNext();
  10089. }, timeout);
  10090. }
  10091. }, callback);
  10092. };
  10093. return AsyncLoop;
  10094. }());
  10095. BABYLON.AsyncLoop = AsyncLoop;
  10096. })(BABYLON || (BABYLON = {}));
  10097. //# sourceMappingURL=babylon.tools.js.map
  10098. var BABYLON;
  10099. (function (BABYLON) {
  10100. var PromiseStates;
  10101. (function (PromiseStates) {
  10102. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10103. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10104. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10105. })(PromiseStates || (PromiseStates = {}));
  10106. var FulFillmentAgregator = /** @class */ (function () {
  10107. function FulFillmentAgregator() {
  10108. this.count = 0;
  10109. this.target = 0;
  10110. this.results = [];
  10111. }
  10112. return FulFillmentAgregator;
  10113. }());
  10114. var InternalPromise = /** @class */ (function () {
  10115. function InternalPromise(resolver) {
  10116. var _this = this;
  10117. this._state = PromiseStates.Pending;
  10118. this._children = new Array();
  10119. this._rejectWasConsumed = false;
  10120. if (!resolver) {
  10121. return;
  10122. }
  10123. try {
  10124. resolver(function (value) {
  10125. _this._resolve(value);
  10126. }, function (reason) {
  10127. _this._reject(reason);
  10128. });
  10129. }
  10130. catch (e) {
  10131. this._reject(e);
  10132. }
  10133. }
  10134. Object.defineProperty(InternalPromise.prototype, "_result", {
  10135. get: function () {
  10136. return this._resultValue;
  10137. },
  10138. set: function (value) {
  10139. this._resultValue = value;
  10140. if (this._parent && this._parent._result === undefined) {
  10141. this._parent._result = value;
  10142. }
  10143. },
  10144. enumerable: true,
  10145. configurable: true
  10146. });
  10147. InternalPromise.prototype.catch = function (onRejected) {
  10148. return this.then(undefined, onRejected);
  10149. };
  10150. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10151. var _this = this;
  10152. var newPromise = new InternalPromise();
  10153. newPromise._onFulfilled = onFulfilled;
  10154. newPromise._onRejected = onRejected;
  10155. // Composition
  10156. this._children.push(newPromise);
  10157. newPromise._parent = this;
  10158. if (this._state !== PromiseStates.Pending) {
  10159. BABYLON.Tools.SetImmediate(function () {
  10160. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10161. var returnedValue = newPromise._resolve(_this._result);
  10162. if (returnedValue !== undefined && returnedValue !== null) {
  10163. if (returnedValue._state !== undefined) {
  10164. var returnedPromise = returnedValue;
  10165. newPromise._children.push(returnedPromise);
  10166. returnedPromise._parent = newPromise;
  10167. newPromise = returnedPromise;
  10168. }
  10169. else {
  10170. newPromise._result = returnedValue;
  10171. }
  10172. }
  10173. }
  10174. else {
  10175. newPromise._reject(_this._reason);
  10176. }
  10177. });
  10178. }
  10179. return newPromise;
  10180. };
  10181. InternalPromise.prototype._moveChildren = function (children) {
  10182. var _this = this;
  10183. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10184. this._children.forEach(function (child) {
  10185. child._parent = _this;
  10186. });
  10187. if (this._state === PromiseStates.Fulfilled) {
  10188. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10189. var child = _b[_i];
  10190. child._resolve(this._result);
  10191. }
  10192. }
  10193. else if (this._state === PromiseStates.Rejected) {
  10194. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10195. var child = _d[_c];
  10196. child._reject(this._reason);
  10197. }
  10198. }
  10199. var _a;
  10200. };
  10201. InternalPromise.prototype._resolve = function (value) {
  10202. try {
  10203. this._state = PromiseStates.Fulfilled;
  10204. var returnedValue = null;
  10205. if (this._onFulfilled) {
  10206. returnedValue = this._onFulfilled(value);
  10207. }
  10208. if (returnedValue !== undefined && returnedValue !== null) {
  10209. if (returnedValue._state !== undefined) {
  10210. // Transmit children
  10211. var returnedPromise = returnedValue;
  10212. returnedPromise._parent = this;
  10213. returnedPromise._moveChildren(this._children);
  10214. value = returnedPromise._result;
  10215. }
  10216. else {
  10217. value = returnedValue;
  10218. }
  10219. }
  10220. this._result = value;
  10221. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10222. var child = _a[_i];
  10223. child._resolve(value);
  10224. }
  10225. this._children.length = 0;
  10226. delete this._onFulfilled;
  10227. delete this._onRejected;
  10228. }
  10229. catch (e) {
  10230. this._reject(e, true);
  10231. }
  10232. };
  10233. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10234. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10235. this._state = PromiseStates.Rejected;
  10236. this._reason = reason;
  10237. if (this._onRejected && !onLocalThrow) {
  10238. try {
  10239. this._onRejected(reason);
  10240. this._rejectWasConsumed = true;
  10241. }
  10242. catch (e) {
  10243. reason = e;
  10244. }
  10245. }
  10246. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10247. var child = _a[_i];
  10248. if (this._rejectWasConsumed) {
  10249. child._resolve(null);
  10250. }
  10251. else {
  10252. child._reject(reason);
  10253. }
  10254. }
  10255. this._children.length = 0;
  10256. delete this._onFulfilled;
  10257. delete this._onRejected;
  10258. };
  10259. InternalPromise.resolve = function (value) {
  10260. var newPromise = new InternalPromise();
  10261. newPromise._resolve(value);
  10262. return newPromise;
  10263. };
  10264. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10265. promise.then(function (value) {
  10266. agregator.results[index] = value;
  10267. agregator.count++;
  10268. if (agregator.count === agregator.target) {
  10269. agregator.rootPromise._resolve(agregator.results);
  10270. }
  10271. return null;
  10272. }, function (reason) {
  10273. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10274. agregator.rootPromise._reject(reason);
  10275. }
  10276. });
  10277. };
  10278. InternalPromise.all = function (promises) {
  10279. var newPromise = new InternalPromise();
  10280. var agregator = new FulFillmentAgregator();
  10281. agregator.target = promises.length;
  10282. agregator.rootPromise = newPromise;
  10283. if (promises.length) {
  10284. for (var index = 0; index < promises.length; index++) {
  10285. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10286. }
  10287. }
  10288. else {
  10289. newPromise._resolve([]);
  10290. }
  10291. return newPromise;
  10292. };
  10293. InternalPromise.race = function (promises) {
  10294. var newPromise = new InternalPromise();
  10295. if (promises.length) {
  10296. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10297. var promise = promises_1[_i];
  10298. promise.then(function (value) {
  10299. if (newPromise) {
  10300. newPromise._resolve(value);
  10301. newPromise = null;
  10302. }
  10303. return null;
  10304. }, function (reason) {
  10305. if (newPromise) {
  10306. newPromise._reject(reason);
  10307. newPromise = null;
  10308. }
  10309. });
  10310. }
  10311. }
  10312. return newPromise;
  10313. };
  10314. return InternalPromise;
  10315. }());
  10316. /**
  10317. * Helper class that provides a small promise polyfill
  10318. */
  10319. var PromisePolyfill = /** @class */ (function () {
  10320. function PromisePolyfill() {
  10321. }
  10322. /**
  10323. * Static function used to check if the polyfill is required
  10324. * If this is the case then the function will inject the polyfill to window.Promise
  10325. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10326. */
  10327. PromisePolyfill.Apply = function (force) {
  10328. if (force === void 0) { force = false; }
  10329. if (force || typeof Promise === 'undefined') {
  10330. var root = window;
  10331. root.Promise = InternalPromise;
  10332. }
  10333. };
  10334. return PromisePolyfill;
  10335. }());
  10336. BABYLON.PromisePolyfill = PromisePolyfill;
  10337. })(BABYLON || (BABYLON = {}));
  10338. //# sourceMappingURL=babylon.promise.js.map
  10339. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10340. var BABYLON;
  10341. (function (BABYLON) {
  10342. /**
  10343. * Helper class to push actions to a pool of workers.
  10344. */
  10345. var WorkerPool = /** @class */ (function () {
  10346. /**
  10347. * Constructor
  10348. * @param workers Array of workers to use for actions
  10349. */
  10350. function WorkerPool(workers) {
  10351. this._pendingActions = new Array();
  10352. this._workerInfos = workers.map(function (worker) { return ({
  10353. worker: worker,
  10354. active: false
  10355. }); });
  10356. }
  10357. /**
  10358. * Terminates all workers and clears any pending actions.
  10359. */
  10360. WorkerPool.prototype.dispose = function () {
  10361. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10362. var workerInfo = _a[_i];
  10363. workerInfo.worker.terminate();
  10364. }
  10365. delete this._workerInfos;
  10366. delete this._pendingActions;
  10367. };
  10368. /**
  10369. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10370. * pended until a worker has completed its action.
  10371. * @param action The action to perform. Call onComplete when the action is complete.
  10372. */
  10373. WorkerPool.prototype.push = function (action) {
  10374. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10375. var workerInfo = _a[_i];
  10376. if (!workerInfo.active) {
  10377. this._execute(workerInfo, action);
  10378. return;
  10379. }
  10380. }
  10381. this._pendingActions.push(action);
  10382. };
  10383. WorkerPool.prototype._execute = function (workerInfo, action) {
  10384. var _this = this;
  10385. workerInfo.active = true;
  10386. action(workerInfo.worker, function () {
  10387. workerInfo.active = false;
  10388. var nextAction = _this._pendingActions.shift();
  10389. if (nextAction) {
  10390. _this._execute(workerInfo, nextAction);
  10391. }
  10392. });
  10393. };
  10394. return WorkerPool;
  10395. }());
  10396. BABYLON.WorkerPool = WorkerPool;
  10397. })(BABYLON || (BABYLON = {}));
  10398. //# sourceMappingURL=babylon.workerPool.js.map
  10399. var BABYLON;
  10400. (function (BABYLON) {
  10401. /**
  10402. * @hidden
  10403. **/
  10404. var _AlphaState = /** @class */ (function () {
  10405. /**
  10406. * Initializes the state.
  10407. */
  10408. function _AlphaState() {
  10409. this._isAlphaBlendDirty = false;
  10410. this._isBlendFunctionParametersDirty = false;
  10411. this._isBlendEquationParametersDirty = false;
  10412. this._isBlendConstantsDirty = false;
  10413. this._alphaBlend = false;
  10414. this._blendFunctionParameters = new Array(4);
  10415. this._blendEquationParameters = new Array(2);
  10416. this._blendConstants = new Array(4);
  10417. this.reset();
  10418. }
  10419. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10420. get: function () {
  10421. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10422. },
  10423. enumerable: true,
  10424. configurable: true
  10425. });
  10426. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10427. get: function () {
  10428. return this._alphaBlend;
  10429. },
  10430. set: function (value) {
  10431. if (this._alphaBlend === value) {
  10432. return;
  10433. }
  10434. this._alphaBlend = value;
  10435. this._isAlphaBlendDirty = true;
  10436. },
  10437. enumerable: true,
  10438. configurable: true
  10439. });
  10440. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10441. if (this._blendConstants[0] === r &&
  10442. this._blendConstants[1] === g &&
  10443. this._blendConstants[2] === b &&
  10444. this._blendConstants[3] === a) {
  10445. return;
  10446. }
  10447. this._blendConstants[0] = r;
  10448. this._blendConstants[1] = g;
  10449. this._blendConstants[2] = b;
  10450. this._blendConstants[3] = a;
  10451. this._isBlendConstantsDirty = true;
  10452. };
  10453. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10454. if (this._blendFunctionParameters[0] === value0 &&
  10455. this._blendFunctionParameters[1] === value1 &&
  10456. this._blendFunctionParameters[2] === value2 &&
  10457. this._blendFunctionParameters[3] === value3) {
  10458. return;
  10459. }
  10460. this._blendFunctionParameters[0] = value0;
  10461. this._blendFunctionParameters[1] = value1;
  10462. this._blendFunctionParameters[2] = value2;
  10463. this._blendFunctionParameters[3] = value3;
  10464. this._isBlendFunctionParametersDirty = true;
  10465. };
  10466. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10467. if (this._blendEquationParameters[0] === rgb &&
  10468. this._blendEquationParameters[1] === alpha) {
  10469. return;
  10470. }
  10471. this._blendEquationParameters[0] = rgb;
  10472. this._blendEquationParameters[1] = alpha;
  10473. this._isBlendEquationParametersDirty = true;
  10474. };
  10475. _AlphaState.prototype.reset = function () {
  10476. this._alphaBlend = false;
  10477. this._blendFunctionParameters[0] = null;
  10478. this._blendFunctionParameters[1] = null;
  10479. this._blendFunctionParameters[2] = null;
  10480. this._blendFunctionParameters[3] = null;
  10481. this._blendEquationParameters[0] = null;
  10482. this._blendEquationParameters[1] = null;
  10483. this._blendConstants[0] = null;
  10484. this._blendConstants[1] = null;
  10485. this._blendConstants[2] = null;
  10486. this._blendConstants[3] = null;
  10487. this._isAlphaBlendDirty = true;
  10488. this._isBlendFunctionParametersDirty = false;
  10489. this._isBlendEquationParametersDirty = false;
  10490. this._isBlendConstantsDirty = false;
  10491. };
  10492. _AlphaState.prototype.apply = function (gl) {
  10493. if (!this.isDirty) {
  10494. return;
  10495. }
  10496. // Alpha blend
  10497. if (this._isAlphaBlendDirty) {
  10498. if (this._alphaBlend) {
  10499. gl.enable(gl.BLEND);
  10500. }
  10501. else {
  10502. gl.disable(gl.BLEND);
  10503. }
  10504. this._isAlphaBlendDirty = false;
  10505. }
  10506. // Alpha function
  10507. if (this._isBlendFunctionParametersDirty) {
  10508. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10509. this._isBlendFunctionParametersDirty = false;
  10510. }
  10511. // Alpha equation
  10512. if (this._isBlendEquationParametersDirty) {
  10513. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10514. this._isBlendEquationParametersDirty = false;
  10515. }
  10516. // Constants
  10517. if (this._isBlendConstantsDirty) {
  10518. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10519. this._isBlendConstantsDirty = false;
  10520. }
  10521. };
  10522. return _AlphaState;
  10523. }());
  10524. BABYLON._AlphaState = _AlphaState;
  10525. })(BABYLON || (BABYLON = {}));
  10526. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10527. var BABYLON;
  10528. (function (BABYLON) {
  10529. /**
  10530. * @hidden
  10531. **/
  10532. var _DepthCullingState = /** @class */ (function () {
  10533. /**
  10534. * Initializes the state.
  10535. */
  10536. function _DepthCullingState() {
  10537. this._isDepthTestDirty = false;
  10538. this._isDepthMaskDirty = false;
  10539. this._isDepthFuncDirty = false;
  10540. this._isCullFaceDirty = false;
  10541. this._isCullDirty = false;
  10542. this._isZOffsetDirty = false;
  10543. this._isFrontFaceDirty = false;
  10544. this.reset();
  10545. }
  10546. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10547. get: function () {
  10548. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10549. },
  10550. enumerable: true,
  10551. configurable: true
  10552. });
  10553. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10554. get: function () {
  10555. return this._zOffset;
  10556. },
  10557. set: function (value) {
  10558. if (this._zOffset === value) {
  10559. return;
  10560. }
  10561. this._zOffset = value;
  10562. this._isZOffsetDirty = true;
  10563. },
  10564. enumerable: true,
  10565. configurable: true
  10566. });
  10567. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10568. get: function () {
  10569. return this._cullFace;
  10570. },
  10571. set: function (value) {
  10572. if (this._cullFace === value) {
  10573. return;
  10574. }
  10575. this._cullFace = value;
  10576. this._isCullFaceDirty = true;
  10577. },
  10578. enumerable: true,
  10579. configurable: true
  10580. });
  10581. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10582. get: function () {
  10583. return this._cull;
  10584. },
  10585. set: function (value) {
  10586. if (this._cull === value) {
  10587. return;
  10588. }
  10589. this._cull = value;
  10590. this._isCullDirty = true;
  10591. },
  10592. enumerable: true,
  10593. configurable: true
  10594. });
  10595. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10596. get: function () {
  10597. return this._depthFunc;
  10598. },
  10599. set: function (value) {
  10600. if (this._depthFunc === value) {
  10601. return;
  10602. }
  10603. this._depthFunc = value;
  10604. this._isDepthFuncDirty = true;
  10605. },
  10606. enumerable: true,
  10607. configurable: true
  10608. });
  10609. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10610. get: function () {
  10611. return this._depthMask;
  10612. },
  10613. set: function (value) {
  10614. if (this._depthMask === value) {
  10615. return;
  10616. }
  10617. this._depthMask = value;
  10618. this._isDepthMaskDirty = true;
  10619. },
  10620. enumerable: true,
  10621. configurable: true
  10622. });
  10623. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10624. get: function () {
  10625. return this._depthTest;
  10626. },
  10627. set: function (value) {
  10628. if (this._depthTest === value) {
  10629. return;
  10630. }
  10631. this._depthTest = value;
  10632. this._isDepthTestDirty = true;
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10638. get: function () {
  10639. return this._frontFace;
  10640. },
  10641. set: function (value) {
  10642. if (this._frontFace === value) {
  10643. return;
  10644. }
  10645. this._frontFace = value;
  10646. this._isFrontFaceDirty = true;
  10647. },
  10648. enumerable: true,
  10649. configurable: true
  10650. });
  10651. _DepthCullingState.prototype.reset = function () {
  10652. this._depthMask = true;
  10653. this._depthTest = true;
  10654. this._depthFunc = null;
  10655. this._cullFace = null;
  10656. this._cull = null;
  10657. this._zOffset = 0;
  10658. this._frontFace = null;
  10659. this._isDepthTestDirty = true;
  10660. this._isDepthMaskDirty = true;
  10661. this._isDepthFuncDirty = false;
  10662. this._isCullFaceDirty = false;
  10663. this._isCullDirty = false;
  10664. this._isZOffsetDirty = false;
  10665. this._isFrontFaceDirty = false;
  10666. };
  10667. _DepthCullingState.prototype.apply = function (gl) {
  10668. if (!this.isDirty) {
  10669. return;
  10670. }
  10671. // Cull
  10672. if (this._isCullDirty) {
  10673. if (this.cull) {
  10674. gl.enable(gl.CULL_FACE);
  10675. }
  10676. else {
  10677. gl.disable(gl.CULL_FACE);
  10678. }
  10679. this._isCullDirty = false;
  10680. }
  10681. // Cull face
  10682. if (this._isCullFaceDirty) {
  10683. gl.cullFace(this.cullFace);
  10684. this._isCullFaceDirty = false;
  10685. }
  10686. // Depth mask
  10687. if (this._isDepthMaskDirty) {
  10688. gl.depthMask(this.depthMask);
  10689. this._isDepthMaskDirty = false;
  10690. }
  10691. // Depth test
  10692. if (this._isDepthTestDirty) {
  10693. if (this.depthTest) {
  10694. gl.enable(gl.DEPTH_TEST);
  10695. }
  10696. else {
  10697. gl.disable(gl.DEPTH_TEST);
  10698. }
  10699. this._isDepthTestDirty = false;
  10700. }
  10701. // Depth func
  10702. if (this._isDepthFuncDirty) {
  10703. gl.depthFunc(this.depthFunc);
  10704. this._isDepthFuncDirty = false;
  10705. }
  10706. // zOffset
  10707. if (this._isZOffsetDirty) {
  10708. if (this.zOffset) {
  10709. gl.enable(gl.POLYGON_OFFSET_FILL);
  10710. gl.polygonOffset(this.zOffset, 0);
  10711. }
  10712. else {
  10713. gl.disable(gl.POLYGON_OFFSET_FILL);
  10714. }
  10715. this._isZOffsetDirty = false;
  10716. }
  10717. // Front face
  10718. if (this._isFrontFaceDirty) {
  10719. gl.frontFace(this.frontFace);
  10720. this._isFrontFaceDirty = false;
  10721. }
  10722. };
  10723. return _DepthCullingState;
  10724. }());
  10725. BABYLON._DepthCullingState = _DepthCullingState;
  10726. })(BABYLON || (BABYLON = {}));
  10727. //# sourceMappingURL=babylon.depthCullingState.js.map
  10728. var BABYLON;
  10729. (function (BABYLON) {
  10730. /**
  10731. * @hidden
  10732. **/
  10733. var _StencilState = /** @class */ (function () {
  10734. function _StencilState() {
  10735. this._isStencilTestDirty = false;
  10736. this._isStencilMaskDirty = false;
  10737. this._isStencilFuncDirty = false;
  10738. this._isStencilOpDirty = false;
  10739. this.reset();
  10740. }
  10741. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10742. get: function () {
  10743. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10749. get: function () {
  10750. return this._stencilFunc;
  10751. },
  10752. set: function (value) {
  10753. if (this._stencilFunc === value) {
  10754. return;
  10755. }
  10756. this._stencilFunc = value;
  10757. this._isStencilFuncDirty = true;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10763. get: function () {
  10764. return this._stencilFuncRef;
  10765. },
  10766. set: function (value) {
  10767. if (this._stencilFuncRef === value) {
  10768. return;
  10769. }
  10770. this._stencilFuncRef = value;
  10771. this._isStencilFuncDirty = true;
  10772. },
  10773. enumerable: true,
  10774. configurable: true
  10775. });
  10776. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10777. get: function () {
  10778. return this._stencilFuncMask;
  10779. },
  10780. set: function (value) {
  10781. if (this._stencilFuncMask === value) {
  10782. return;
  10783. }
  10784. this._stencilFuncMask = value;
  10785. this._isStencilFuncDirty = true;
  10786. },
  10787. enumerable: true,
  10788. configurable: true
  10789. });
  10790. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10791. get: function () {
  10792. return this._stencilOpStencilFail;
  10793. },
  10794. set: function (value) {
  10795. if (this._stencilOpStencilFail === value) {
  10796. return;
  10797. }
  10798. this._stencilOpStencilFail = value;
  10799. this._isStencilOpDirty = true;
  10800. },
  10801. enumerable: true,
  10802. configurable: true
  10803. });
  10804. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10805. get: function () {
  10806. return this._stencilOpDepthFail;
  10807. },
  10808. set: function (value) {
  10809. if (this._stencilOpDepthFail === value) {
  10810. return;
  10811. }
  10812. this._stencilOpDepthFail = value;
  10813. this._isStencilOpDirty = true;
  10814. },
  10815. enumerable: true,
  10816. configurable: true
  10817. });
  10818. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10819. get: function () {
  10820. return this._stencilOpStencilDepthPass;
  10821. },
  10822. set: function (value) {
  10823. if (this._stencilOpStencilDepthPass === value) {
  10824. return;
  10825. }
  10826. this._stencilOpStencilDepthPass = value;
  10827. this._isStencilOpDirty = true;
  10828. },
  10829. enumerable: true,
  10830. configurable: true
  10831. });
  10832. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10833. get: function () {
  10834. return this._stencilMask;
  10835. },
  10836. set: function (value) {
  10837. if (this._stencilMask === value) {
  10838. return;
  10839. }
  10840. this._stencilMask = value;
  10841. this._isStencilMaskDirty = true;
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10847. get: function () {
  10848. return this._stencilTest;
  10849. },
  10850. set: function (value) {
  10851. if (this._stencilTest === value) {
  10852. return;
  10853. }
  10854. this._stencilTest = value;
  10855. this._isStencilTestDirty = true;
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. _StencilState.prototype.reset = function () {
  10861. this._stencilTest = false;
  10862. this._stencilMask = 0xFF;
  10863. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10864. this._stencilFuncRef = 1;
  10865. this._stencilFuncMask = 0xFF;
  10866. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10867. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10868. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10869. this._isStencilTestDirty = true;
  10870. this._isStencilMaskDirty = true;
  10871. this._isStencilFuncDirty = true;
  10872. this._isStencilOpDirty = true;
  10873. };
  10874. _StencilState.prototype.apply = function (gl) {
  10875. if (!this.isDirty) {
  10876. return;
  10877. }
  10878. // Stencil test
  10879. if (this._isStencilTestDirty) {
  10880. if (this.stencilTest) {
  10881. gl.enable(gl.STENCIL_TEST);
  10882. }
  10883. else {
  10884. gl.disable(gl.STENCIL_TEST);
  10885. }
  10886. this._isStencilTestDirty = false;
  10887. }
  10888. // Stencil mask
  10889. if (this._isStencilMaskDirty) {
  10890. gl.stencilMask(this.stencilMask);
  10891. this._isStencilMaskDirty = false;
  10892. }
  10893. // Stencil func
  10894. if (this._isStencilFuncDirty) {
  10895. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10896. this._isStencilFuncDirty = false;
  10897. }
  10898. // Stencil op
  10899. if (this._isStencilOpDirty) {
  10900. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10901. this._isStencilOpDirty = false;
  10902. }
  10903. };
  10904. return _StencilState;
  10905. }());
  10906. BABYLON._StencilState = _StencilState;
  10907. })(BABYLON || (BABYLON = {}));
  10908. //# sourceMappingURL=babylon.stencilState.js.map
  10909. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10910. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10911. s = arguments[i];
  10912. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10913. t[p] = s[p];
  10914. }
  10915. return t;
  10916. };
  10917. var BABYLON;
  10918. (function (BABYLON) {
  10919. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10920. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10921. };
  10922. var compileRawShader = function (gl, source, type) {
  10923. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10924. gl.shaderSource(shader, source);
  10925. gl.compileShader(shader);
  10926. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10927. var log = gl.getShaderInfoLog(shader);
  10928. if (log) {
  10929. throw new Error(log);
  10930. }
  10931. }
  10932. if (!shader) {
  10933. throw new Error("Something went wrong while compile the shader.");
  10934. }
  10935. return shader;
  10936. };
  10937. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10938. var magFilter = gl.NEAREST;
  10939. var minFilter = gl.NEAREST;
  10940. switch (samplingMode) {
  10941. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10942. magFilter = gl.LINEAR;
  10943. if (generateMipMaps) {
  10944. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10945. }
  10946. else {
  10947. minFilter = gl.LINEAR;
  10948. }
  10949. break;
  10950. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10951. magFilter = gl.LINEAR;
  10952. if (generateMipMaps) {
  10953. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10954. }
  10955. else {
  10956. minFilter = gl.LINEAR;
  10957. }
  10958. break;
  10959. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10960. magFilter = gl.NEAREST;
  10961. if (generateMipMaps) {
  10962. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10963. }
  10964. else {
  10965. minFilter = gl.NEAREST;
  10966. }
  10967. break;
  10968. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10969. magFilter = gl.NEAREST;
  10970. if (generateMipMaps) {
  10971. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10972. }
  10973. else {
  10974. minFilter = gl.NEAREST;
  10975. }
  10976. break;
  10977. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10978. magFilter = gl.NEAREST;
  10979. if (generateMipMaps) {
  10980. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10981. }
  10982. else {
  10983. minFilter = gl.LINEAR;
  10984. }
  10985. break;
  10986. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10987. magFilter = gl.NEAREST;
  10988. if (generateMipMaps) {
  10989. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10990. }
  10991. else {
  10992. minFilter = gl.LINEAR;
  10993. }
  10994. break;
  10995. case BABYLON.Texture.NEAREST_LINEAR:
  10996. magFilter = gl.NEAREST;
  10997. minFilter = gl.LINEAR;
  10998. break;
  10999. case BABYLON.Texture.NEAREST_NEAREST:
  11000. magFilter = gl.NEAREST;
  11001. minFilter = gl.NEAREST;
  11002. break;
  11003. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11004. magFilter = gl.LINEAR;
  11005. if (generateMipMaps) {
  11006. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11007. }
  11008. else {
  11009. minFilter = gl.NEAREST;
  11010. }
  11011. break;
  11012. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11013. magFilter = gl.LINEAR;
  11014. if (generateMipMaps) {
  11015. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11016. }
  11017. else {
  11018. minFilter = gl.NEAREST;
  11019. }
  11020. break;
  11021. case BABYLON.Texture.LINEAR_LINEAR:
  11022. magFilter = gl.LINEAR;
  11023. minFilter = gl.LINEAR;
  11024. break;
  11025. case BABYLON.Texture.LINEAR_NEAREST:
  11026. magFilter = gl.LINEAR;
  11027. minFilter = gl.NEAREST;
  11028. break;
  11029. }
  11030. return {
  11031. min: minFilter,
  11032. mag: magFilter
  11033. };
  11034. };
  11035. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11036. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11037. var img;
  11038. var onload = function () {
  11039. loadedImages[index] = img;
  11040. loadedImages._internalCount++;
  11041. if (scene) {
  11042. scene._removePendingData(img);
  11043. }
  11044. if (loadedImages._internalCount === 6) {
  11045. onfinish(loadedImages);
  11046. }
  11047. };
  11048. var onerror = function (message, exception) {
  11049. if (scene) {
  11050. scene._removePendingData(img);
  11051. }
  11052. if (onErrorCallBack) {
  11053. onErrorCallBack(message, exception);
  11054. }
  11055. };
  11056. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11057. if (scene) {
  11058. scene._addPendingData(img);
  11059. }
  11060. };
  11061. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11062. if (onError === void 0) { onError = null; }
  11063. var loadedImages = [];
  11064. loadedImages._internalCount = 0;
  11065. for (var index = 0; index < 6; index++) {
  11066. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11067. }
  11068. };
  11069. var BufferPointer = /** @class */ (function () {
  11070. function BufferPointer() {
  11071. }
  11072. return BufferPointer;
  11073. }());
  11074. /**
  11075. * Interface for attribute information associated with buffer instanciation
  11076. */
  11077. var InstancingAttributeInfo = /** @class */ (function () {
  11078. function InstancingAttributeInfo() {
  11079. }
  11080. return InstancingAttributeInfo;
  11081. }());
  11082. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11083. /**
  11084. * Define options used to create a render target texture
  11085. */
  11086. var RenderTargetCreationOptions = /** @class */ (function () {
  11087. function RenderTargetCreationOptions() {
  11088. }
  11089. return RenderTargetCreationOptions;
  11090. }());
  11091. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11092. /**
  11093. * Define options used to create a depth texture
  11094. */
  11095. var DepthTextureCreationOptions = /** @class */ (function () {
  11096. function DepthTextureCreationOptions() {
  11097. }
  11098. return DepthTextureCreationOptions;
  11099. }());
  11100. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11101. /**
  11102. * Class used to describe the capabilities of the engine relatively to the current browser
  11103. */
  11104. var EngineCapabilities = /** @class */ (function () {
  11105. function EngineCapabilities() {
  11106. }
  11107. return EngineCapabilities;
  11108. }());
  11109. BABYLON.EngineCapabilities = EngineCapabilities;
  11110. /**
  11111. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11112. */
  11113. var Engine = /** @class */ (function () {
  11114. /**
  11115. * Creates a new engine
  11116. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11117. * @param antialias defines enable antialiasing (default: false)
  11118. * @param options defines further options to be sent to the getContext() function
  11119. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11120. */
  11121. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11122. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11123. var _this = this;
  11124. // Public members
  11125. /**
  11126. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11127. */
  11128. this.forcePOTTextures = false;
  11129. /**
  11130. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11131. */
  11132. this.isFullscreen = false;
  11133. /**
  11134. * Gets a boolean indicating if the pointer is currently locked
  11135. */
  11136. this.isPointerLock = false;
  11137. /**
  11138. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11139. */
  11140. this.cullBackFaces = true;
  11141. /**
  11142. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11143. */
  11144. this.renderEvenInBackground = true;
  11145. /**
  11146. * Gets or sets a boolean indicating that cache can be kept between frames
  11147. */
  11148. this.preventCacheWipeBetweenFrames = false;
  11149. /**
  11150. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11151. **/
  11152. this.enableOfflineSupport = false;
  11153. /**
  11154. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11155. **/
  11156. this.disableManifestCheck = false;
  11157. /**
  11158. * Gets the list of created scenes
  11159. */
  11160. this.scenes = new Array();
  11161. /**
  11162. * Gets the list of created postprocesses
  11163. */
  11164. this.postProcesses = new Array();
  11165. // Observables
  11166. /**
  11167. * Observable event triggered each time the rendering canvas is resized
  11168. */
  11169. this.onResizeObservable = new BABYLON.Observable();
  11170. /**
  11171. * Observable event triggered each time the canvas loses focus
  11172. */
  11173. this.onCanvasBlurObservable = new BABYLON.Observable();
  11174. /**
  11175. * Observable event triggered each time the canvas gains focus
  11176. */
  11177. this.onCanvasFocusObservable = new BABYLON.Observable();
  11178. /**
  11179. * Observable event triggered each time the canvas receives pointerout event
  11180. */
  11181. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11182. /**
  11183. * Observable event triggered before each texture is initialized
  11184. */
  11185. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11186. //WebVR
  11187. this._vrDisplay = undefined;
  11188. this._vrSupported = false;
  11189. this._vrExclusivePointerMode = false;
  11190. // Uniform buffers list
  11191. /**
  11192. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11193. */
  11194. this.disableUniformBuffers = false;
  11195. /** @hidden */
  11196. this._uniformBuffers = new Array();
  11197. // Observables
  11198. /**
  11199. * Observable raised when the engine begins a new frame
  11200. */
  11201. this.onBeginFrameObservable = new BABYLON.Observable();
  11202. /**
  11203. * Observable raised when the engine ends the current frame
  11204. */
  11205. this.onEndFrameObservable = new BABYLON.Observable();
  11206. /**
  11207. * Observable raised when the engine is about to compile a shader
  11208. */
  11209. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11210. /**
  11211. * Observable raised when the engine has jsut compiled a shader
  11212. */
  11213. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11214. this._windowIsBackground = false;
  11215. this._webGLVersion = 1.0;
  11216. /** @hidden */
  11217. this._badOS = false;
  11218. /** @hidden */
  11219. this._badDesktopOS = false;
  11220. /**
  11221. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11222. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11223. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11224. */
  11225. this.disableTextureBindingOptimization = false;
  11226. /**
  11227. * Observable signaled when VR display mode changes
  11228. */
  11229. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11230. /**
  11231. * Observable signaled when VR request present is complete
  11232. */
  11233. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11234. /**
  11235. * Observable signaled when VR request present starts
  11236. */
  11237. this.onVRRequestPresentStart = new BABYLON.Observable();
  11238. this._colorWrite = true;
  11239. /** @hidden */
  11240. this._drawCalls = new BABYLON.PerfCounter();
  11241. /** @hidden */
  11242. this._textureCollisions = new BABYLON.PerfCounter();
  11243. this._renderingQueueLaunched = false;
  11244. this._activeRenderLoops = new Array();
  11245. // Deterministic lockstepMaxSteps
  11246. this._deterministicLockstep = false;
  11247. this._lockstepMaxSteps = 4;
  11248. // Lost context
  11249. /**
  11250. * Observable signaled when a context lost event is raised
  11251. */
  11252. this.onContextLostObservable = new BABYLON.Observable();
  11253. /**
  11254. * Observable signaled when a context restored event is raised
  11255. */
  11256. this.onContextRestoredObservable = new BABYLON.Observable();
  11257. this._contextWasLost = false;
  11258. this._doNotHandleContextLost = false;
  11259. // FPS
  11260. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11261. this._fps = 60;
  11262. this._deltaTime = 0;
  11263. /**
  11264. * Turn this value on if you want to pause FPS computation when in background
  11265. */
  11266. this.disablePerformanceMonitorInBackground = false;
  11267. // States
  11268. /** @hidden */
  11269. this._depthCullingState = new BABYLON._DepthCullingState();
  11270. /** @hidden */
  11271. this._stencilState = new BABYLON._StencilState();
  11272. /** @hidden */
  11273. this._alphaState = new BABYLON._AlphaState();
  11274. /** @hidden */
  11275. this._alphaMode = Engine.ALPHA_DISABLE;
  11276. // Cache
  11277. this._internalTexturesCache = new Array();
  11278. /** @hidden */
  11279. this._activeChannel = 0;
  11280. this._currentTextureChannel = -1;
  11281. /** @hidden */
  11282. this._boundTexturesCache = {};
  11283. this._compiledEffects = {};
  11284. this._vertexAttribArraysEnabled = [];
  11285. this._uintIndicesCurrentlySet = false;
  11286. this._currentBoundBuffer = new Array();
  11287. this._currentBufferPointers = new Array();
  11288. this._currentInstanceLocations = new Array();
  11289. this._currentInstanceBuffers = new Array();
  11290. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11291. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11292. this._vaoRecordInProgress = false;
  11293. this._mustWipeVertexAttributes = false;
  11294. this._nextFreeTextureSlots = new Array();
  11295. this._maxSimultaneousTextures = 0;
  11296. this._activeRequests = new Array();
  11297. // Hardware supported Compressed Textures
  11298. this._texturesSupported = new Array();
  11299. this._onVRFullScreenTriggered = function () {
  11300. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11301. //get the old size before we change
  11302. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11303. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11304. //get the width and height, change the render size
  11305. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11306. _this.setHardwareScalingLevel(1);
  11307. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11308. }
  11309. else {
  11310. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11311. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11312. }
  11313. };
  11314. this._boundUniforms = {};
  11315. // Register promises
  11316. BABYLON.PromisePolyfill.Apply();
  11317. var canvas = null;
  11318. Engine.Instances.push(this);
  11319. if (!canvasOrContext) {
  11320. return;
  11321. }
  11322. options = options || {};
  11323. if (canvasOrContext.getContext) {
  11324. canvas = canvasOrContext;
  11325. this._renderingCanvas = canvas;
  11326. if (antialias != null) {
  11327. options.antialias = antialias;
  11328. }
  11329. if (options.deterministicLockstep === undefined) {
  11330. options.deterministicLockstep = false;
  11331. }
  11332. if (options.lockstepMaxSteps === undefined) {
  11333. options.lockstepMaxSteps = 4;
  11334. }
  11335. if (options.preserveDrawingBuffer === undefined) {
  11336. options.preserveDrawingBuffer = false;
  11337. }
  11338. if (options.audioEngine === undefined) {
  11339. options.audioEngine = true;
  11340. }
  11341. if (options.stencil === undefined) {
  11342. options.stencil = true;
  11343. }
  11344. this._deterministicLockstep = options.deterministicLockstep;
  11345. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11346. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11347. // Exceptions
  11348. if (navigator && navigator.userAgent) {
  11349. var ua = navigator.userAgent;
  11350. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11351. var exception = _a[_i];
  11352. var key = exception.key;
  11353. var targets = exception.targets;
  11354. if (ua.indexOf(key) > -1) {
  11355. if (exception.capture && exception.captureConstraint) {
  11356. var capture = exception.capture;
  11357. var constraint = exception.captureConstraint;
  11358. var regex = new RegExp(capture);
  11359. var matches = regex.exec(ua);
  11360. if (matches && matches.length > 0) {
  11361. var capturedValue = parseInt(matches[matches.length - 1]);
  11362. if (capturedValue >= constraint) {
  11363. continue;
  11364. }
  11365. }
  11366. }
  11367. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11368. var target = targets_1[_b];
  11369. switch (target) {
  11370. case "uniformBuffer":
  11371. this.disableUniformBuffers = true;
  11372. break;
  11373. case "textureBindingOptimization":
  11374. this.disableTextureBindingOptimization = true;
  11375. break;
  11376. }
  11377. }
  11378. }
  11379. }
  11380. }
  11381. // GL
  11382. if (!options.disableWebGL2Support) {
  11383. try {
  11384. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11385. if (this._gl) {
  11386. this._webGLVersion = 2.0;
  11387. }
  11388. }
  11389. catch (e) {
  11390. // Do nothing
  11391. }
  11392. }
  11393. if (!this._gl) {
  11394. if (!canvas) {
  11395. throw new Error("The provided canvas is null or undefined.");
  11396. }
  11397. try {
  11398. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11399. }
  11400. catch (e) {
  11401. throw new Error("WebGL not supported");
  11402. }
  11403. }
  11404. if (!this._gl) {
  11405. throw new Error("WebGL not supported");
  11406. }
  11407. this._onCanvasFocus = function () {
  11408. _this.onCanvasFocusObservable.notifyObservers(_this);
  11409. };
  11410. this._onCanvasBlur = function () {
  11411. _this.onCanvasBlurObservable.notifyObservers(_this);
  11412. };
  11413. canvas.addEventListener("focus", this._onCanvasFocus);
  11414. canvas.addEventListener("blur", this._onCanvasBlur);
  11415. this._onBlur = function () {
  11416. if (_this.disablePerformanceMonitorInBackground) {
  11417. _this._performanceMonitor.disable();
  11418. }
  11419. _this._windowIsBackground = true;
  11420. };
  11421. this._onFocus = function () {
  11422. if (_this.disablePerformanceMonitorInBackground) {
  11423. _this._performanceMonitor.enable();
  11424. }
  11425. _this._windowIsBackground = false;
  11426. };
  11427. this._onCanvasPointerOut = function (ev) {
  11428. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11429. };
  11430. window.addEventListener("blur", this._onBlur);
  11431. window.addEventListener("focus", this._onFocus);
  11432. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11433. // Context lost
  11434. if (!this._doNotHandleContextLost) {
  11435. this._onContextLost = function (evt) {
  11436. evt.preventDefault();
  11437. _this._contextWasLost = true;
  11438. BABYLON.Tools.Warn("WebGL context lost.");
  11439. _this.onContextLostObservable.notifyObservers(_this);
  11440. };
  11441. this._onContextRestored = function (evt) {
  11442. // Adding a timeout to avoid race condition at browser level
  11443. setTimeout(function () {
  11444. // Rebuild gl context
  11445. _this._initGLContext();
  11446. // Rebuild effects
  11447. _this._rebuildEffects();
  11448. // Rebuild textures
  11449. _this._rebuildInternalTextures();
  11450. // Rebuild buffers
  11451. _this._rebuildBuffers();
  11452. // Cache
  11453. _this.wipeCaches(true);
  11454. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11455. _this.onContextRestoredObservable.notifyObservers(_this);
  11456. _this._contextWasLost = false;
  11457. }, 0);
  11458. };
  11459. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11460. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11461. }
  11462. }
  11463. else {
  11464. this._gl = canvasOrContext;
  11465. this._renderingCanvas = this._gl.canvas;
  11466. if (this._gl.renderbufferStorageMultisample) {
  11467. this._webGLVersion = 2.0;
  11468. }
  11469. options.stencil = this._gl.getContextAttributes().stencil;
  11470. }
  11471. // Viewport
  11472. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11473. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11474. this.resize();
  11475. this._isStencilEnable = options.stencil ? true : false;
  11476. this._initGLContext();
  11477. if (canvas) {
  11478. // Fullscreen
  11479. this._onFullscreenChange = function () {
  11480. if (document.fullscreen !== undefined) {
  11481. _this.isFullscreen = document.fullscreen;
  11482. }
  11483. else if (document.mozFullScreen !== undefined) {
  11484. _this.isFullscreen = document.mozFullScreen;
  11485. }
  11486. else if (document.webkitIsFullScreen !== undefined) {
  11487. _this.isFullscreen = document.webkitIsFullScreen;
  11488. }
  11489. else if (document.msIsFullScreen !== undefined) {
  11490. _this.isFullscreen = document.msIsFullScreen;
  11491. }
  11492. // Pointer lock
  11493. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11494. canvas.requestPointerLock = canvas.requestPointerLock ||
  11495. canvas.msRequestPointerLock ||
  11496. canvas.mozRequestPointerLock ||
  11497. canvas.webkitRequestPointerLock;
  11498. if (canvas.requestPointerLock) {
  11499. canvas.requestPointerLock();
  11500. }
  11501. }
  11502. };
  11503. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11504. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11505. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11506. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11507. // Pointer lock
  11508. this._onPointerLockChange = function () {
  11509. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11510. document.webkitPointerLockElement === canvas ||
  11511. document.msPointerLockElement === canvas ||
  11512. document.pointerLockElement === canvas);
  11513. };
  11514. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11515. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11516. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11517. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11518. this._onVRDisplayPointerRestricted = function () {
  11519. if (canvas) {
  11520. canvas.requestPointerLock();
  11521. }
  11522. };
  11523. this._onVRDisplayPointerUnrestricted = function () {
  11524. document.exitPointerLock();
  11525. };
  11526. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11527. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11528. }
  11529. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11530. Engine.audioEngine = new BABYLON.AudioEngine();
  11531. }
  11532. // Prepare buffer pointers
  11533. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11534. this._currentBufferPointers[i] = new BufferPointer();
  11535. }
  11536. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11537. // Load WebVR Devices
  11538. if (options.autoEnableWebVR) {
  11539. this.initWebVR();
  11540. }
  11541. // Detect if we are running on a faulty buggy OS.
  11542. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11543. // Detect if we are running on a faulty buggy desktop OS.
  11544. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11545. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11546. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11547. }
  11548. Object.defineProperty(Engine, "LastCreatedEngine", {
  11549. /**
  11550. * Gets the latest created engine
  11551. */
  11552. get: function () {
  11553. if (Engine.Instances.length === 0) {
  11554. return null;
  11555. }
  11556. return Engine.Instances[Engine.Instances.length - 1];
  11557. },
  11558. enumerable: true,
  11559. configurable: true
  11560. });
  11561. Object.defineProperty(Engine, "LastCreatedScene", {
  11562. /**
  11563. * Gets the latest created scene
  11564. */
  11565. get: function () {
  11566. var lastCreatedEngine = Engine.LastCreatedEngine;
  11567. if (!lastCreatedEngine) {
  11568. return null;
  11569. }
  11570. if (lastCreatedEngine.scenes.length === 0) {
  11571. return null;
  11572. }
  11573. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11574. },
  11575. enumerable: true,
  11576. configurable: true
  11577. });
  11578. /**
  11579. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11580. * @param flag defines which part of the materials must be marked as dirty
  11581. * @param predicate defines a predicate used to filter which materials should be affected
  11582. */
  11583. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11584. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11585. var engine = Engine.Instances[engineIndex];
  11586. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11587. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11588. }
  11589. }
  11590. };
  11591. Object.defineProperty(Engine, "NEVER", {
  11592. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11593. get: function () {
  11594. return Engine._NEVER;
  11595. },
  11596. enumerable: true,
  11597. configurable: true
  11598. });
  11599. Object.defineProperty(Engine, "ALWAYS", {
  11600. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  11601. get: function () {
  11602. return Engine._ALWAYS;
  11603. },
  11604. enumerable: true,
  11605. configurable: true
  11606. });
  11607. Object.defineProperty(Engine, "LESS", {
  11608. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11609. get: function () {
  11610. return Engine._LESS;
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Object.defineProperty(Engine, "EQUAL", {
  11616. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11617. get: function () {
  11618. return Engine._EQUAL;
  11619. },
  11620. enumerable: true,
  11621. configurable: true
  11622. });
  11623. Object.defineProperty(Engine, "LEQUAL", {
  11624. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  11625. get: function () {
  11626. return Engine._LEQUAL;
  11627. },
  11628. enumerable: true,
  11629. configurable: true
  11630. });
  11631. Object.defineProperty(Engine, "GREATER", {
  11632. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11633. get: function () {
  11634. return Engine._GREATER;
  11635. },
  11636. enumerable: true,
  11637. configurable: true
  11638. });
  11639. Object.defineProperty(Engine, "GEQUAL", {
  11640. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  11641. get: function () {
  11642. return Engine._GEQUAL;
  11643. },
  11644. enumerable: true,
  11645. configurable: true
  11646. });
  11647. Object.defineProperty(Engine, "NOTEQUAL", {
  11648. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  11649. get: function () {
  11650. return Engine._NOTEQUAL;
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. Object.defineProperty(Engine, "KEEP", {
  11656. /** Passed to stencilOperation to specify that stencil value must be kept */
  11657. get: function () {
  11658. return Engine._KEEP;
  11659. },
  11660. enumerable: true,
  11661. configurable: true
  11662. });
  11663. Object.defineProperty(Engine, "REPLACE", {
  11664. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11665. get: function () {
  11666. return Engine._REPLACE;
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. Object.defineProperty(Engine, "INCR", {
  11672. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11673. get: function () {
  11674. return Engine._INCR;
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine, "DECR", {
  11680. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11681. get: function () {
  11682. return Engine._DECR;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Object.defineProperty(Engine, "INVERT", {
  11688. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11689. get: function () {
  11690. return Engine._INVERT;
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Engine, "INCR_WRAP", {
  11696. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11697. get: function () {
  11698. return Engine._INCR_WRAP;
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. Object.defineProperty(Engine, "DECR_WRAP", {
  11704. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11705. get: function () {
  11706. return Engine._DECR_WRAP;
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11712. // Alpha
  11713. /** Defines that alpha blending is disabled */
  11714. get: function () {
  11715. return Engine._ALPHA_DISABLE;
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11721. /** Defines that alpha blending to SRC + DEST */
  11722. get: function () {
  11723. return Engine._ALPHA_ONEONE;
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Engine, "ALPHA_ADD", {
  11729. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11730. get: function () {
  11731. return Engine._ALPHA_ADD;
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11737. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11738. get: function () {
  11739. return Engine._ALPHA_COMBINE;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11745. /** Defines that alpha blending to DEST - SRC * DEST */
  11746. get: function () {
  11747. return Engine._ALPHA_SUBTRACT;
  11748. },
  11749. enumerable: true,
  11750. configurable: true
  11751. });
  11752. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11753. /** Defines that alpha blending to SRC * DEST */
  11754. get: function () {
  11755. return Engine._ALPHA_MULTIPLY;
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11761. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11762. get: function () {
  11763. return Engine._ALPHA_MAXIMIZED;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11769. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11770. get: function () {
  11771. return Engine._ALPHA_PREMULTIPLIED;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11777. /**
  11778. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11779. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11780. */
  11781. get: function () {
  11782. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11788. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11789. get: function () {
  11790. return Engine._ALPHA_INTERPOLATE;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11796. /**
  11797. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11798. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11799. */
  11800. get: function () {
  11801. return Engine._ALPHA_SCREENMODE;
  11802. },
  11803. enumerable: true,
  11804. configurable: true
  11805. });
  11806. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11807. // Delays
  11808. /** Defines that the ressource is not delayed*/
  11809. get: function () {
  11810. return Engine._DELAYLOADSTATE_NONE;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11816. /** Defines that the ressource was successfully delay loaded */
  11817. get: function () {
  11818. return Engine._DELAYLOADSTATE_LOADED;
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11824. /** Defines that the ressource is currently delay loading */
  11825. get: function () {
  11826. return Engine._DELAYLOADSTATE_LOADING;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11832. /** Defines that the ressource is delayed and has not started loading */
  11833. get: function () {
  11834. return Engine._DELAYLOADSTATE_NOTLOADED;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11840. /** ALPHA */
  11841. get: function () {
  11842. return Engine._TEXTUREFORMAT_ALPHA;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11848. /** LUMINANCE */
  11849. get: function () {
  11850. return Engine._TEXTUREFORMAT_LUMINANCE;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11856. /**
  11857. * R32F
  11858. */
  11859. get: function () {
  11860. return Engine._TEXTUREFORMAT_R32F;
  11861. },
  11862. enumerable: true,
  11863. configurable: true
  11864. });
  11865. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11866. /**
  11867. * RG32F
  11868. */
  11869. get: function () {
  11870. return Engine._TEXTUREFORMAT_RG32F;
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11876. /**
  11877. * RGB32F
  11878. */
  11879. get: function () {
  11880. return Engine._TEXTUREFORMAT_RGB32F;
  11881. },
  11882. enumerable: true,
  11883. configurable: true
  11884. });
  11885. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11886. /**
  11887. * RGBA32F
  11888. */
  11889. get: function () {
  11890. return Engine._TEXTUREFORMAT_RGBA32F;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11896. /** LUMINANCE_ALPHA */
  11897. get: function () {
  11898. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11904. /** RGB */
  11905. get: function () {
  11906. return Engine._TEXTUREFORMAT_RGB;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11912. /** RGBA */
  11913. get: function () {
  11914. return Engine._TEXTUREFORMAT_RGBA;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11920. /** UNSIGNED_INT */
  11921. get: function () {
  11922. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11928. /** FLOAT */
  11929. get: function () {
  11930. return Engine._TEXTURETYPE_FLOAT;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11936. /** HALF_FLOAT */
  11937. get: function () {
  11938. return Engine._TEXTURETYPE_HALF_FLOAT;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11944. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11945. get: function () {
  11946. return Engine._SCALEMODE_FLOOR;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11952. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11953. get: function () {
  11954. return Engine._SCALEMODE_NEAREST;
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11960. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11961. get: function () {
  11962. return Engine._SCALEMODE_CEILING;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine, "Version", {
  11968. /**
  11969. * Returns the current version of the framework
  11970. */
  11971. get: function () {
  11972. return "3.2.0-rc.2";
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11978. /**
  11979. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11980. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11981. */
  11982. get: function () {
  11983. return this._vrExclusivePointerMode;
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11989. /**
  11990. * Gets a boolean indicating that the engine supports uniform buffers
  11991. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11992. */
  11993. get: function () {
  11994. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12000. /**
  12001. * Gets a boolean indicating that only power of 2 textures are supported
  12002. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12003. */
  12004. get: function () {
  12005. return this._webGLVersion < 2 || this.forcePOTTextures;
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12011. /**
  12012. * Gets the performance monitor attached to this engine
  12013. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12014. */
  12015. get: function () {
  12016. return this._performanceMonitor;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12022. /**
  12023. * Gets the list of texture formats supported
  12024. */
  12025. get: function () {
  12026. return this._texturesSupported;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12032. /**
  12033. * Gets the list of texture formats in use
  12034. */
  12035. get: function () {
  12036. return this._textureFormatInUse;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(Engine.prototype, "currentViewport", {
  12042. /**
  12043. * Gets the current viewport
  12044. */
  12045. get: function () {
  12046. return this._cachedViewport;
  12047. },
  12048. enumerable: true,
  12049. configurable: true
  12050. });
  12051. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12052. /**
  12053. * Gets the default empty texture
  12054. */
  12055. get: function () {
  12056. if (!this._emptyTexture) {
  12057. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12058. }
  12059. return this._emptyTexture;
  12060. },
  12061. enumerable: true,
  12062. configurable: true
  12063. });
  12064. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12065. /**
  12066. * Gets the default empty 3D texture
  12067. */
  12068. get: function () {
  12069. if (!this._emptyTexture3D) {
  12070. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12071. }
  12072. return this._emptyTexture3D;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12078. /**
  12079. * Gets the default empty cube texture
  12080. */
  12081. get: function () {
  12082. if (!this._emptyCubeTexture) {
  12083. var faceData = new Uint8Array(4);
  12084. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12085. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12086. }
  12087. return this._emptyCubeTexture;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Engine.prototype._rebuildInternalTextures = function () {
  12093. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12094. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12095. var internalTexture = currentState_1[_i];
  12096. internalTexture._rebuild();
  12097. }
  12098. };
  12099. Engine.prototype._rebuildEffects = function () {
  12100. for (var key in this._compiledEffects) {
  12101. var effect = this._compiledEffects[key];
  12102. effect._prepareEffect();
  12103. }
  12104. BABYLON.Effect.ResetCache();
  12105. };
  12106. Engine.prototype._rebuildBuffers = function () {
  12107. // Index / Vertex
  12108. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12109. var scene = _a[_i];
  12110. scene.resetCachedMaterial();
  12111. scene._rebuildGeometries();
  12112. scene._rebuildTextures();
  12113. }
  12114. // Uniforms
  12115. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12116. var uniformBuffer = _c[_b];
  12117. uniformBuffer._rebuild();
  12118. }
  12119. };
  12120. Engine.prototype._initGLContext = function () {
  12121. // Caps
  12122. this._caps = new EngineCapabilities();
  12123. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12124. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12125. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12126. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12127. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12128. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12129. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12130. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12131. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12132. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12133. // Infos
  12134. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12135. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12136. if (rendererInfo != null) {
  12137. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12138. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12139. }
  12140. if (!this._glVendor) {
  12141. this._glVendor = "Unknown vendor";
  12142. }
  12143. if (!this._glRenderer) {
  12144. this._glRenderer = "Unknown renderer";
  12145. }
  12146. // Constants
  12147. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12148. if (this._gl.RGBA16F !== 0x881A) {
  12149. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12150. }
  12151. if (this._gl.RGBA32F !== 0x8814) {
  12152. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12153. }
  12154. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12155. this._gl.DEPTH24_STENCIL8 = 35056;
  12156. }
  12157. // Extensions
  12158. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12159. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12160. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12161. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12162. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12163. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12164. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12165. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  12166. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12167. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12168. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12169. this._caps.highPrecisionShaderSupported = true;
  12170. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12171. if (this._caps.timerQuery) {
  12172. if (this._webGLVersion === 1) {
  12173. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12174. }
  12175. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12176. }
  12177. // Checks if some of the format renders first to allow the use of webgl inspector.
  12178. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12179. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12180. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12181. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12182. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12183. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12184. if (this._webGLVersion > 1) {
  12185. this._gl.HALF_FLOAT_OES = 0x140B;
  12186. }
  12187. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12188. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12189. // Draw buffers
  12190. if (this._webGLVersion > 1) {
  12191. this._caps.drawBuffersExtension = true;
  12192. }
  12193. else {
  12194. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12195. if (drawBuffersExtension !== null) {
  12196. this._caps.drawBuffersExtension = true;
  12197. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12198. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12199. for (var i = 0; i < 16; i++) {
  12200. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12201. }
  12202. }
  12203. else {
  12204. this._caps.drawBuffersExtension = false;
  12205. }
  12206. }
  12207. // Depth Texture
  12208. if (this._webGLVersion > 1) {
  12209. this._caps.depthTextureExtension = true;
  12210. }
  12211. else {
  12212. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12213. if (depthTextureExtension != null) {
  12214. this._caps.depthTextureExtension = true;
  12215. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12216. }
  12217. }
  12218. // Vertex array object
  12219. if (this._webGLVersion > 1) {
  12220. this._caps.vertexArrayObject = true;
  12221. }
  12222. else {
  12223. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12224. if (vertexArrayObjectExtension != null) {
  12225. this._caps.vertexArrayObject = true;
  12226. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12227. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12228. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12229. }
  12230. else {
  12231. this._caps.vertexArrayObject = false;
  12232. }
  12233. }
  12234. // Instances count
  12235. if (this._webGLVersion > 1) {
  12236. this._caps.instancedArrays = true;
  12237. }
  12238. else {
  12239. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12240. if (instanceExtension != null) {
  12241. this._caps.instancedArrays = true;
  12242. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12243. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12244. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12245. }
  12246. else {
  12247. this._caps.instancedArrays = false;
  12248. }
  12249. }
  12250. // Intelligently add supported compressed formats in order to check for.
  12251. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12252. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12253. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12254. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12255. if (this._caps.astc)
  12256. this.texturesSupported.push('-astc.ktx');
  12257. if (this._caps.s3tc)
  12258. this.texturesSupported.push('-dxt.ktx');
  12259. if (this._caps.pvrtc)
  12260. this.texturesSupported.push('-pvrtc.ktx');
  12261. if (this._caps.etc2)
  12262. this.texturesSupported.push('-etc2.ktx');
  12263. if (this._caps.etc1)
  12264. this.texturesSupported.push('-etc1.ktx');
  12265. if (this._gl.getShaderPrecisionFormat) {
  12266. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12267. if (highp) {
  12268. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12269. }
  12270. }
  12271. // Depth buffer
  12272. this.setDepthBuffer(true);
  12273. this.setDepthFunctionToLessOrEqual();
  12274. this.setDepthWrite(true);
  12275. // Texture maps
  12276. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12277. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12278. this._nextFreeTextureSlots.push(slot);
  12279. }
  12280. };
  12281. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12282. /**
  12283. * Gets version of the current webGL context
  12284. */
  12285. get: function () {
  12286. return this._webGLVersion;
  12287. },
  12288. enumerable: true,
  12289. configurable: true
  12290. });
  12291. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12292. /**
  12293. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12294. */
  12295. get: function () {
  12296. return this._isStencilEnable;
  12297. },
  12298. enumerable: true,
  12299. configurable: true
  12300. });
  12301. Engine.prototype._prepareWorkingCanvas = function () {
  12302. if (this._workingCanvas) {
  12303. return;
  12304. }
  12305. this._workingCanvas = document.createElement("canvas");
  12306. var context = this._workingCanvas.getContext("2d");
  12307. if (context) {
  12308. this._workingContext = context;
  12309. }
  12310. };
  12311. /**
  12312. * Reset the texture cache to empty state
  12313. */
  12314. Engine.prototype.resetTextureCache = function () {
  12315. for (var key in this._boundTexturesCache) {
  12316. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12317. continue;
  12318. }
  12319. var boundTexture = this._boundTexturesCache[key];
  12320. if (boundTexture) {
  12321. this._removeDesignatedSlot(boundTexture);
  12322. }
  12323. this._boundTexturesCache[key] = null;
  12324. }
  12325. if (!this.disableTextureBindingOptimization) {
  12326. this._nextFreeTextureSlots = [];
  12327. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12328. this._nextFreeTextureSlots.push(slot);
  12329. }
  12330. }
  12331. this._currentTextureChannel = -1;
  12332. };
  12333. /**
  12334. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12335. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12336. * @returns true if engine is in deterministic lock step mode
  12337. */
  12338. Engine.prototype.isDeterministicLockStep = function () {
  12339. return this._deterministicLockstep;
  12340. };
  12341. /**
  12342. * Gets the max steps when engine is running in deterministic lock step
  12343. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12344. * @returns the max steps
  12345. */
  12346. Engine.prototype.getLockstepMaxSteps = function () {
  12347. return this._lockstepMaxSteps;
  12348. };
  12349. /**
  12350. * Gets an object containing information about the current webGL context
  12351. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12352. */
  12353. Engine.prototype.getGlInfo = function () {
  12354. return {
  12355. vendor: this._glVendor,
  12356. renderer: this._glRenderer,
  12357. version: this._glVersion
  12358. };
  12359. };
  12360. /**
  12361. * Gets current aspect ratio
  12362. * @param camera defines the camera to use to get the aspect ratio
  12363. * @param useScreen defines if screen size must be used (or the current render target if any)
  12364. * @returns a number defining the aspect ratio
  12365. */
  12366. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12367. if (useScreen === void 0) { useScreen = false; }
  12368. var viewport = camera.viewport;
  12369. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12370. };
  12371. /**
  12372. * Gets the current render width
  12373. * @param useScreen defines if screen size must be used (or the current render target if any)
  12374. * @returns a number defining the current render width
  12375. */
  12376. Engine.prototype.getRenderWidth = function (useScreen) {
  12377. if (useScreen === void 0) { useScreen = false; }
  12378. if (!useScreen && this._currentRenderTarget) {
  12379. return this._currentRenderTarget.width;
  12380. }
  12381. return this._gl.drawingBufferWidth;
  12382. };
  12383. /**
  12384. * Gets the current render height
  12385. * @param useScreen defines if screen size must be used (or the current render target if any)
  12386. * @returns a number defining the current render height
  12387. */
  12388. Engine.prototype.getRenderHeight = function (useScreen) {
  12389. if (useScreen === void 0) { useScreen = false; }
  12390. if (!useScreen && this._currentRenderTarget) {
  12391. return this._currentRenderTarget.height;
  12392. }
  12393. return this._gl.drawingBufferHeight;
  12394. };
  12395. /**
  12396. * Gets the HTML canvas attached with the current webGL context
  12397. * @returns a HTML canvas
  12398. */
  12399. Engine.prototype.getRenderingCanvas = function () {
  12400. return this._renderingCanvas;
  12401. };
  12402. /**
  12403. * Gets the client rect of the HTML canvas attached with the current webGL context
  12404. * @returns a client rectanglee
  12405. */
  12406. Engine.prototype.getRenderingCanvasClientRect = function () {
  12407. if (!this._renderingCanvas) {
  12408. return null;
  12409. }
  12410. return this._renderingCanvas.getBoundingClientRect();
  12411. };
  12412. /**
  12413. * Defines the hardware scaling level.
  12414. * By default the hardware scaling level is computed from the window device ratio.
  12415. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12416. * @param level defines the level to use
  12417. */
  12418. Engine.prototype.setHardwareScalingLevel = function (level) {
  12419. this._hardwareScalingLevel = level;
  12420. this.resize();
  12421. };
  12422. /**
  12423. * Gets the current hardware scaling level.
  12424. * By default the hardware scaling level is computed from the window device ratio.
  12425. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12426. * @returns a number indicating the current hardware scaling level
  12427. */
  12428. Engine.prototype.getHardwareScalingLevel = function () {
  12429. return this._hardwareScalingLevel;
  12430. };
  12431. /**
  12432. * Gets the list of loaded textures
  12433. * @returns an array containing all loaded textures
  12434. */
  12435. Engine.prototype.getLoadedTexturesCache = function () {
  12436. return this._internalTexturesCache;
  12437. };
  12438. /**
  12439. * Gets the object containing all engine capabilities
  12440. * @returns the EngineCapabilities object
  12441. */
  12442. Engine.prototype.getCaps = function () {
  12443. return this._caps;
  12444. };
  12445. Object.defineProperty(Engine.prototype, "drawCalls", {
  12446. /** @hidden */
  12447. get: function () {
  12448. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12449. return 0;
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12455. /** @hidden */
  12456. get: function () {
  12457. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12458. return null;
  12459. },
  12460. enumerable: true,
  12461. configurable: true
  12462. });
  12463. /**
  12464. * Gets the current depth function
  12465. * @returns a number defining the depth function
  12466. */
  12467. Engine.prototype.getDepthFunction = function () {
  12468. return this._depthCullingState.depthFunc;
  12469. };
  12470. /**
  12471. * Sets the current depth function
  12472. * @param depthFunc defines the function to use
  12473. */
  12474. Engine.prototype.setDepthFunction = function (depthFunc) {
  12475. this._depthCullingState.depthFunc = depthFunc;
  12476. };
  12477. /**
  12478. * Sets the current depth function to GREATER
  12479. */
  12480. Engine.prototype.setDepthFunctionToGreater = function () {
  12481. this._depthCullingState.depthFunc = this._gl.GREATER;
  12482. };
  12483. /**
  12484. * Sets the current depth function to GEQUAL
  12485. */
  12486. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12487. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12488. };
  12489. /**
  12490. * Sets the current depth function to LESS
  12491. */
  12492. Engine.prototype.setDepthFunctionToLess = function () {
  12493. this._depthCullingState.depthFunc = this._gl.LESS;
  12494. };
  12495. /**
  12496. * Sets the current depth function to LEQUAL
  12497. */
  12498. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12499. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12500. };
  12501. /**
  12502. * Gets a boolean indicating if stencil buffer is enabled
  12503. * @returns the current stencil buffer state
  12504. */
  12505. Engine.prototype.getStencilBuffer = function () {
  12506. return this._stencilState.stencilTest;
  12507. };
  12508. /**
  12509. * Enable or disable the stencil buffer
  12510. * @param enable defines if the stencil buffer must be enabled or disabled
  12511. */
  12512. Engine.prototype.setStencilBuffer = function (enable) {
  12513. this._stencilState.stencilTest = enable;
  12514. };
  12515. /**
  12516. * Gets the current stencil mask
  12517. * @returns a number defining the new stencil mask to use
  12518. */
  12519. Engine.prototype.getStencilMask = function () {
  12520. return this._stencilState.stencilMask;
  12521. };
  12522. /**
  12523. * Sets the current stencil mask
  12524. * @param mask defines the new stencil mask to use
  12525. */
  12526. Engine.prototype.setStencilMask = function (mask) {
  12527. this._stencilState.stencilMask = mask;
  12528. };
  12529. /**
  12530. * Gets the current stencil function
  12531. * @returns a number defining the stencil function to use
  12532. */
  12533. Engine.prototype.getStencilFunction = function () {
  12534. return this._stencilState.stencilFunc;
  12535. };
  12536. /**
  12537. * Gets the current stencil reference value
  12538. * @returns a number defining the stencil reference value to use
  12539. */
  12540. Engine.prototype.getStencilFunctionReference = function () {
  12541. return this._stencilState.stencilFuncRef;
  12542. };
  12543. /**
  12544. * Gets the current stencil mask
  12545. * @returns a number defining the stencil mask to use
  12546. */
  12547. Engine.prototype.getStencilFunctionMask = function () {
  12548. return this._stencilState.stencilFuncMask;
  12549. };
  12550. /**
  12551. * Sets the current stencil function
  12552. * @param stencilFunc defines the new stencil function to use
  12553. */
  12554. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12555. this._stencilState.stencilFunc = stencilFunc;
  12556. };
  12557. /**
  12558. * Sets the current stencil reference
  12559. * @param reference defines the new stencil reference to use
  12560. */
  12561. Engine.prototype.setStencilFunctionReference = function (reference) {
  12562. this._stencilState.stencilFuncRef = reference;
  12563. };
  12564. /**
  12565. * Sets the current stencil mask
  12566. * @param mask defines the new stencil mask to use
  12567. */
  12568. Engine.prototype.setStencilFunctionMask = function (mask) {
  12569. this._stencilState.stencilFuncMask = mask;
  12570. };
  12571. /**
  12572. * Gets the current stencil operation when stencil fails
  12573. * @returns a number defining stencil operation to use when stencil fails
  12574. */
  12575. Engine.prototype.getStencilOperationFail = function () {
  12576. return this._stencilState.stencilOpStencilFail;
  12577. };
  12578. /**
  12579. * Gets the current stencil operation when depth fails
  12580. * @returns a number defining stencil operation to use when depth fails
  12581. */
  12582. Engine.prototype.getStencilOperationDepthFail = function () {
  12583. return this._stencilState.stencilOpDepthFail;
  12584. };
  12585. /**
  12586. * Gets the current stencil operation when stencil passes
  12587. * @returns a number defining stencil operation to use when stencil passes
  12588. */
  12589. Engine.prototype.getStencilOperationPass = function () {
  12590. return this._stencilState.stencilOpStencilDepthPass;
  12591. };
  12592. /**
  12593. * Sets the stencil operation to use when stencil fails
  12594. * @param operation defines the stencil operation to use when stencil fails
  12595. */
  12596. Engine.prototype.setStencilOperationFail = function (operation) {
  12597. this._stencilState.stencilOpStencilFail = operation;
  12598. };
  12599. /**
  12600. * Sets the stencil operation to use when depth fails
  12601. * @param operation defines the stencil operation to use when depth fails
  12602. */
  12603. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12604. this._stencilState.stencilOpDepthFail = operation;
  12605. };
  12606. /**
  12607. * Sets the stencil operation to use when stencil passes
  12608. * @param operation defines the stencil operation to use when stencil passes
  12609. */
  12610. Engine.prototype.setStencilOperationPass = function (operation) {
  12611. this._stencilState.stencilOpStencilDepthPass = operation;
  12612. };
  12613. /**
  12614. * Sets a boolean indicating if the dithering state is enabled or disabled
  12615. * @param value defines the dithering state
  12616. */
  12617. Engine.prototype.setDitheringState = function (value) {
  12618. if (value) {
  12619. this._gl.enable(this._gl.DITHER);
  12620. }
  12621. else {
  12622. this._gl.disable(this._gl.DITHER);
  12623. }
  12624. };
  12625. /**
  12626. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12627. * @param value defines the rasterizer state
  12628. */
  12629. Engine.prototype.setRasterizerState = function (value) {
  12630. if (value) {
  12631. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12632. }
  12633. else {
  12634. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12635. }
  12636. };
  12637. /**
  12638. * stop executing a render loop function and remove it from the execution array
  12639. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12640. */
  12641. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12642. if (!renderFunction) {
  12643. this._activeRenderLoops = [];
  12644. return;
  12645. }
  12646. var index = this._activeRenderLoops.indexOf(renderFunction);
  12647. if (index >= 0) {
  12648. this._activeRenderLoops.splice(index, 1);
  12649. }
  12650. };
  12651. /** @hidden */
  12652. Engine.prototype._renderLoop = function () {
  12653. if (!this._contextWasLost) {
  12654. var shouldRender = true;
  12655. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12656. shouldRender = false;
  12657. }
  12658. if (shouldRender) {
  12659. // Start new frame
  12660. this.beginFrame();
  12661. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12662. var renderFunction = this._activeRenderLoops[index];
  12663. renderFunction();
  12664. }
  12665. // Present
  12666. this.endFrame();
  12667. }
  12668. }
  12669. if (this._activeRenderLoops.length > 0) {
  12670. // Register new frame
  12671. var requester = null;
  12672. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12673. requester = this._vrDisplay;
  12674. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12675. }
  12676. else {
  12677. this._renderingQueueLaunched = false;
  12678. }
  12679. };
  12680. /**
  12681. * Register and execute a render loop. The engine can have more than one render function
  12682. * @param renderFunction defines the function to continuously execute
  12683. */
  12684. Engine.prototype.runRenderLoop = function (renderFunction) {
  12685. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12686. return;
  12687. }
  12688. this._activeRenderLoops.push(renderFunction);
  12689. if (!this._renderingQueueLaunched) {
  12690. this._renderingQueueLaunched = true;
  12691. this._bindedRenderFunction = this._renderLoop.bind(this);
  12692. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12693. }
  12694. };
  12695. /**
  12696. * Toggle full screen mode
  12697. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12698. * @param options defines an option object to be sent to the requestFullscreen function
  12699. */
  12700. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12701. if (this.isFullscreen) {
  12702. BABYLON.Tools.ExitFullscreen();
  12703. }
  12704. else {
  12705. this._pointerLockRequested = requestPointerLock;
  12706. if (this._renderingCanvas) {
  12707. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12708. }
  12709. }
  12710. };
  12711. /**
  12712. * Clear the current render buffer or the current render target (if any is set up)
  12713. * @param color defines the color to use
  12714. * @param backBuffer defines if the back buffer must be cleared
  12715. * @param depth defines if the depth buffer must be cleared
  12716. * @param stencil defines if the stencil buffer must be cleared
  12717. */
  12718. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12719. if (stencil === void 0) { stencil = false; }
  12720. this.applyStates();
  12721. var mode = 0;
  12722. if (backBuffer && color) {
  12723. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12724. mode |= this._gl.COLOR_BUFFER_BIT;
  12725. }
  12726. if (depth) {
  12727. this._gl.clearDepth(1.0);
  12728. mode |= this._gl.DEPTH_BUFFER_BIT;
  12729. }
  12730. if (stencil) {
  12731. this._gl.clearStencil(0);
  12732. mode |= this._gl.STENCIL_BUFFER_BIT;
  12733. }
  12734. this._gl.clear(mode);
  12735. };
  12736. /**
  12737. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12738. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12739. * @param y defines the y-coordinate of the corner of the clear rectangle
  12740. * @param width defines the width of the clear rectangle
  12741. * @param height defines the height of the clear rectangle
  12742. * @param clearColor defines the clear color
  12743. */
  12744. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12745. var gl = this._gl;
  12746. // Save state
  12747. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12748. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12749. // Change state
  12750. gl.enable(gl.SCISSOR_TEST);
  12751. gl.scissor(x, y, width, height);
  12752. // Clear
  12753. this.clear(clearColor, true, true, true);
  12754. // Restore state
  12755. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12756. if (curScissor === true) {
  12757. gl.enable(gl.SCISSOR_TEST);
  12758. }
  12759. else {
  12760. gl.disable(gl.SCISSOR_TEST);
  12761. }
  12762. };
  12763. /**
  12764. * Set the WebGL's viewport
  12765. * @param viewport defines the viewport element to be used
  12766. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12767. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12768. */
  12769. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12770. var width = requiredWidth || this.getRenderWidth();
  12771. var height = requiredHeight || this.getRenderHeight();
  12772. var x = viewport.x || 0;
  12773. var y = viewport.y || 0;
  12774. this._cachedViewport = viewport;
  12775. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12776. };
  12777. /**
  12778. * Directly set the WebGL Viewport
  12779. * @param x defines the x coordinate of the viewport (in screen space)
  12780. * @param y defines the y coordinate of the viewport (in screen space)
  12781. * @param width defines the width of the viewport (in screen space)
  12782. * @param height defines the height of the viewport (in screen space)
  12783. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  12784. */
  12785. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12786. var currentViewport = this._cachedViewport;
  12787. this._cachedViewport = null;
  12788. this._gl.viewport(x, y, width, height);
  12789. return currentViewport;
  12790. };
  12791. /**
  12792. * Begin a new frame
  12793. */
  12794. Engine.prototype.beginFrame = function () {
  12795. this.onBeginFrameObservable.notifyObservers(this);
  12796. this._measureFps();
  12797. };
  12798. /**
  12799. * Enf the current frame
  12800. */
  12801. Engine.prototype.endFrame = function () {
  12802. // Force a flush in case we are using a bad OS.
  12803. if (this._badOS) {
  12804. this.flushFramebuffer();
  12805. }
  12806. // Submit frame to the vr device, if enabled
  12807. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12808. // TODO: We should only submit the frame if we read frameData successfully.
  12809. this._vrDisplay.submitFrame();
  12810. }
  12811. this.onEndFrameObservable.notifyObservers(this);
  12812. };
  12813. /**
  12814. * Resize the view according to the canvas' size
  12815. */
  12816. Engine.prototype.resize = function () {
  12817. // We're not resizing the size of the canvas while in VR mode & presenting
  12818. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12819. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12820. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12821. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12822. }
  12823. };
  12824. /**
  12825. * Force a specific size of the canvas
  12826. * @param width defines the new canvas' width
  12827. * @param height defines the new canvas' height
  12828. */
  12829. Engine.prototype.setSize = function (width, height) {
  12830. if (!this._renderingCanvas) {
  12831. return;
  12832. }
  12833. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12834. return;
  12835. }
  12836. this._renderingCanvas.width = width;
  12837. this._renderingCanvas.height = height;
  12838. for (var index = 0; index < this.scenes.length; index++) {
  12839. var scene = this.scenes[index];
  12840. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12841. var cam = scene.cameras[camIndex];
  12842. cam._currentRenderId = 0;
  12843. }
  12844. }
  12845. if (this.onResizeObservable.hasObservers) {
  12846. this.onResizeObservable.notifyObservers(this);
  12847. }
  12848. };
  12849. // WebVR functions
  12850. /**
  12851. * Gets a boolean indicating if a webVR device was detected
  12852. * @returns true if a webVR device was detected
  12853. */
  12854. Engine.prototype.isVRDevicePresent = function () {
  12855. return !!this._vrDisplay;
  12856. };
  12857. /**
  12858. * Gets the current webVR device
  12859. * @returns the current webVR device (or null)
  12860. */
  12861. Engine.prototype.getVRDevice = function () {
  12862. return this._vrDisplay;
  12863. };
  12864. /**
  12865. * Initializes a webVR display and starts listening to display change events
  12866. * The onVRDisplayChangedObservable will be notified upon these changes
  12867. * @returns The onVRDisplayChangedObservable
  12868. */
  12869. Engine.prototype.initWebVR = function () {
  12870. this.initWebVRAsync();
  12871. return this.onVRDisplayChangedObservable;
  12872. };
  12873. /**
  12874. * Initializes a webVR display and starts listening to display change events
  12875. * The onVRDisplayChangedObservable will be notified upon these changes
  12876. * @returns A promise containing a VRDisplay and if vr is supported
  12877. */
  12878. Engine.prototype.initWebVRAsync = function () {
  12879. var _this = this;
  12880. var notifyObservers = function () {
  12881. var eventArgs = {
  12882. vrDisplay: _this._vrDisplay,
  12883. vrSupported: _this._vrSupported
  12884. };
  12885. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12886. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12887. };
  12888. if (!this._onVrDisplayConnect) {
  12889. this._onVrDisplayConnect = function (event) {
  12890. _this._vrDisplay = event.display;
  12891. notifyObservers();
  12892. };
  12893. this._onVrDisplayDisconnect = function () {
  12894. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12895. _this._vrDisplay = undefined;
  12896. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12897. notifyObservers();
  12898. };
  12899. this._onVrDisplayPresentChange = function () {
  12900. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12901. };
  12902. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12903. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12904. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12905. }
  12906. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12907. this._webVRInitPromise.then(notifyObservers);
  12908. return this._webVRInitPromise;
  12909. };
  12910. /**
  12911. * Call this function to switch to webVR mode
  12912. * Will do nothing if webVR is not supported or if there is no webVR device
  12913. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12914. */
  12915. Engine.prototype.enableVR = function () {
  12916. var _this = this;
  12917. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12918. var onResolved = function () {
  12919. _this.onVRRequestPresentComplete.notifyObservers(true);
  12920. _this._onVRFullScreenTriggered();
  12921. };
  12922. var onRejected = function () {
  12923. _this.onVRRequestPresentComplete.notifyObservers(false);
  12924. };
  12925. this.onVRRequestPresentStart.notifyObservers(this);
  12926. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12927. }
  12928. };
  12929. /**
  12930. * Call this function to leave webVR mode
  12931. * Will do nothing if webVR is not supported or if there is no webVR device
  12932. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12933. */
  12934. Engine.prototype.disableVR = function () {
  12935. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12936. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12937. }
  12938. };
  12939. Engine.prototype._getVRDisplaysAsync = function () {
  12940. var _this = this;
  12941. return new Promise(function (res, rej) {
  12942. if (navigator.getVRDisplays) {
  12943. navigator.getVRDisplays().then(function (devices) {
  12944. _this._vrSupported = true;
  12945. // note that devices may actually be an empty array. This is fine;
  12946. // we expect this._vrDisplay to be undefined in this case.
  12947. _this._vrDisplay = devices[0];
  12948. res({
  12949. vrDisplay: _this._vrDisplay,
  12950. vrSupported: _this._vrSupported
  12951. });
  12952. });
  12953. }
  12954. else {
  12955. _this._vrDisplay = undefined;
  12956. _this._vrSupported = false;
  12957. res({
  12958. vrDisplay: _this._vrDisplay,
  12959. vrSupported: _this._vrSupported
  12960. });
  12961. }
  12962. });
  12963. };
  12964. /**
  12965. * Binds the frame buffer to the specified texture.
  12966. * @param texture The texture to render to or null for the default canvas
  12967. * @param faceIndex The face of the texture to render to in case of cube texture
  12968. * @param requiredWidth The width of the target to render to
  12969. * @param requiredHeight The height of the target to render to
  12970. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12971. * @param depthStencilTexture The depth stencil texture to use to render
  12972. */
  12973. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12974. if (this._currentRenderTarget) {
  12975. this.unBindFramebuffer(this._currentRenderTarget);
  12976. }
  12977. this._currentRenderTarget = texture;
  12978. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12979. var gl = this._gl;
  12980. if (texture.isCube) {
  12981. if (faceIndex === undefined) {
  12982. faceIndex = 0;
  12983. }
  12984. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12985. if (depthStencilTexture) {
  12986. if (depthStencilTexture._generateStencilBuffer) {
  12987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12988. }
  12989. else {
  12990. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12991. }
  12992. }
  12993. }
  12994. if (this._cachedViewport && !forceFullscreenViewport) {
  12995. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12996. }
  12997. else {
  12998. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12999. }
  13000. this.wipeCaches();
  13001. };
  13002. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13003. if (this._currentFramebuffer !== framebuffer) {
  13004. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13005. this._currentFramebuffer = framebuffer;
  13006. }
  13007. };
  13008. /**
  13009. * Unbind the current render target texture from the webGL context
  13010. * @param texture defines the render target texture to unbind
  13011. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13012. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13013. */
  13014. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13015. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13016. this._currentRenderTarget = null;
  13017. // If MSAA, we need to bitblt back to main texture
  13018. var gl = this._gl;
  13019. if (texture._MSAAFramebuffer) {
  13020. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13021. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13022. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13023. }
  13024. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13025. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13026. gl.generateMipmap(gl.TEXTURE_2D);
  13027. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13028. }
  13029. if (onBeforeUnbind) {
  13030. if (texture._MSAAFramebuffer) {
  13031. // Bind the correct framebuffer
  13032. this.bindUnboundFramebuffer(texture._framebuffer);
  13033. }
  13034. onBeforeUnbind();
  13035. }
  13036. this.bindUnboundFramebuffer(null);
  13037. };
  13038. /**
  13039. * Unbind a list of render target textures from the webGL context
  13040. * This is used only when drawBuffer extension or webGL2 are active
  13041. * @param textures defines the render target textures to unbind
  13042. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13043. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13044. */
  13045. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13046. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13047. this._currentRenderTarget = null;
  13048. // If MSAA, we need to bitblt back to main texture
  13049. var gl = this._gl;
  13050. if (textures[0]._MSAAFramebuffer) {
  13051. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13052. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13053. var attachments = textures[0]._attachments;
  13054. if (!attachments) {
  13055. attachments = new Array(textures.length);
  13056. textures[0]._attachments = attachments;
  13057. }
  13058. for (var i = 0; i < textures.length; i++) {
  13059. var texture = textures[i];
  13060. for (var j = 0; j < attachments.length; j++) {
  13061. attachments[j] = gl.NONE;
  13062. }
  13063. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13064. gl.readBuffer(attachments[i]);
  13065. gl.drawBuffers(attachments);
  13066. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13067. }
  13068. for (var i = 0; i < attachments.length; i++) {
  13069. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13070. }
  13071. gl.drawBuffers(attachments);
  13072. }
  13073. for (var i = 0; i < textures.length; i++) {
  13074. var texture = textures[i];
  13075. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13076. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13077. gl.generateMipmap(gl.TEXTURE_2D);
  13078. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13079. }
  13080. }
  13081. if (onBeforeUnbind) {
  13082. if (textures[0]._MSAAFramebuffer) {
  13083. // Bind the correct framebuffer
  13084. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13085. }
  13086. onBeforeUnbind();
  13087. }
  13088. this.bindUnboundFramebuffer(null);
  13089. };
  13090. /**
  13091. * Force the mipmap generation for the given render target texture
  13092. * @param texture defines the render target texture to use
  13093. */
  13094. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13095. if (texture.generateMipMaps) {
  13096. var gl = this._gl;
  13097. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13098. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13099. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13100. }
  13101. };
  13102. /**
  13103. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13104. */
  13105. Engine.prototype.flushFramebuffer = function () {
  13106. this._gl.flush();
  13107. };
  13108. /**
  13109. * Unbind the current render target and bind the default framebuffer
  13110. */
  13111. Engine.prototype.restoreDefaultFramebuffer = function () {
  13112. if (this._currentRenderTarget) {
  13113. this.unBindFramebuffer(this._currentRenderTarget);
  13114. }
  13115. else {
  13116. this.bindUnboundFramebuffer(null);
  13117. }
  13118. if (this._cachedViewport) {
  13119. this.setViewport(this._cachedViewport);
  13120. }
  13121. this.wipeCaches();
  13122. };
  13123. // UBOs
  13124. /**
  13125. * Create an uniform buffer
  13126. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13127. * @param elements defines the content of the uniform buffer
  13128. * @returns the webGL uniform buffer
  13129. */
  13130. Engine.prototype.createUniformBuffer = function (elements) {
  13131. var ubo = this._gl.createBuffer();
  13132. if (!ubo) {
  13133. throw new Error("Unable to create uniform buffer");
  13134. }
  13135. this.bindUniformBuffer(ubo);
  13136. if (elements instanceof Float32Array) {
  13137. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13138. }
  13139. else {
  13140. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13141. }
  13142. this.bindUniformBuffer(null);
  13143. ubo.references = 1;
  13144. return ubo;
  13145. };
  13146. /**
  13147. * Create a dynamic uniform buffer
  13148. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13149. * @param elements defines the content of the uniform buffer
  13150. * @returns the webGL uniform buffer
  13151. */
  13152. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13153. var ubo = this._gl.createBuffer();
  13154. if (!ubo) {
  13155. throw new Error("Unable to create dynamic uniform buffer");
  13156. }
  13157. this.bindUniformBuffer(ubo);
  13158. if (elements instanceof Float32Array) {
  13159. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13160. }
  13161. else {
  13162. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13163. }
  13164. this.bindUniformBuffer(null);
  13165. ubo.references = 1;
  13166. return ubo;
  13167. };
  13168. /**
  13169. * Update an existing uniform buffer
  13170. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13171. * @param uniformBuffer defines the target uniform buffer
  13172. * @param elements defines the content to update
  13173. * @param offset defines the offset in the uniform buffer where update should start
  13174. * @param count defines the size of the data to update
  13175. */
  13176. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13177. this.bindUniformBuffer(uniformBuffer);
  13178. if (offset === undefined) {
  13179. offset = 0;
  13180. }
  13181. if (count === undefined) {
  13182. if (elements instanceof Float32Array) {
  13183. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13184. }
  13185. else {
  13186. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13187. }
  13188. }
  13189. else {
  13190. if (elements instanceof Float32Array) {
  13191. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13192. }
  13193. else {
  13194. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13195. }
  13196. }
  13197. this.bindUniformBuffer(null);
  13198. };
  13199. // VBOs
  13200. Engine.prototype._resetVertexBufferBinding = function () {
  13201. this.bindArrayBuffer(null);
  13202. this._cachedVertexBuffers = null;
  13203. };
  13204. /**
  13205. * Creates a vertex buffer
  13206. * @param data the data for the vertex buffer
  13207. * @returns the new WebGL static buffer
  13208. */
  13209. Engine.prototype.createVertexBuffer = function (data) {
  13210. var vbo = this._gl.createBuffer();
  13211. if (!vbo) {
  13212. throw new Error("Unable to create vertex buffer");
  13213. }
  13214. this.bindArrayBuffer(vbo);
  13215. if (data instanceof Array) {
  13216. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13217. }
  13218. else {
  13219. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13220. }
  13221. this._resetVertexBufferBinding();
  13222. vbo.references = 1;
  13223. return vbo;
  13224. };
  13225. /**
  13226. * Creates a dynamic vertex buffer
  13227. * @param data the data for the dynamic vertex buffer
  13228. * @returns the new WebGL dynamic buffer
  13229. */
  13230. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13231. var vbo = this._gl.createBuffer();
  13232. if (!vbo) {
  13233. throw new Error("Unable to create dynamic vertex buffer");
  13234. }
  13235. this.bindArrayBuffer(vbo);
  13236. if (data instanceof Array) {
  13237. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13238. }
  13239. else {
  13240. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13241. }
  13242. this._resetVertexBufferBinding();
  13243. vbo.references = 1;
  13244. return vbo;
  13245. };
  13246. /**
  13247. * Update a dynamic index buffer
  13248. * @param indexBuffer defines the target index buffer
  13249. * @param indices defines the data to update
  13250. * @param offset defines the offset in the target index buffer where update should start
  13251. */
  13252. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13253. if (offset === void 0) { offset = 0; }
  13254. // Force cache update
  13255. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13256. this.bindIndexBuffer(indexBuffer);
  13257. var arrayBuffer;
  13258. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13259. arrayBuffer = indices;
  13260. }
  13261. else {
  13262. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13263. }
  13264. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13265. this._resetIndexBufferBinding();
  13266. };
  13267. /**
  13268. * Updates a dynamic vertex buffer.
  13269. * @param vertexBuffer the vertex buffer to update
  13270. * @param data the data used to update the vertex buffer
  13271. * @param byteOffset the byte offset of the data
  13272. * @param byteLength the byte length of the data
  13273. */
  13274. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13275. this.bindArrayBuffer(vertexBuffer);
  13276. if (byteOffset === undefined) {
  13277. byteOffset = 0;
  13278. }
  13279. if (byteLength === undefined) {
  13280. if (data instanceof Array) {
  13281. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13282. }
  13283. else {
  13284. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13285. }
  13286. }
  13287. else {
  13288. if (data instanceof Array) {
  13289. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13290. }
  13291. else {
  13292. if (data instanceof ArrayBuffer) {
  13293. data = new Uint8Array(data, byteOffset, byteLength);
  13294. }
  13295. else {
  13296. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13297. }
  13298. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13299. }
  13300. }
  13301. this._resetVertexBufferBinding();
  13302. };
  13303. Engine.prototype._resetIndexBufferBinding = function () {
  13304. this.bindIndexBuffer(null);
  13305. this._cachedIndexBuffer = null;
  13306. };
  13307. /**
  13308. * Creates a new index buffer
  13309. * @param indices defines the content of the index buffer
  13310. * @param updatable defines if the index buffer must be updatable
  13311. * @returns a new webGL buffer
  13312. */
  13313. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13314. var vbo = this._gl.createBuffer();
  13315. if (!vbo) {
  13316. throw new Error("Unable to create index buffer");
  13317. }
  13318. this.bindIndexBuffer(vbo);
  13319. // Check for 32 bits indices
  13320. var arrayBuffer;
  13321. var need32Bits = false;
  13322. if (indices instanceof Uint16Array) {
  13323. arrayBuffer = indices;
  13324. }
  13325. else {
  13326. //check 32 bit support
  13327. if (this._caps.uintIndices) {
  13328. if (indices instanceof Uint32Array) {
  13329. arrayBuffer = indices;
  13330. need32Bits = true;
  13331. }
  13332. else {
  13333. //number[] or Int32Array, check if 32 bit is necessary
  13334. for (var index = 0; index < indices.length; index++) {
  13335. if (indices[index] > 65535) {
  13336. need32Bits = true;
  13337. break;
  13338. }
  13339. }
  13340. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13341. }
  13342. }
  13343. else {
  13344. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13345. arrayBuffer = new Uint16Array(indices);
  13346. }
  13347. }
  13348. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13349. this._resetIndexBufferBinding();
  13350. vbo.references = 1;
  13351. vbo.is32Bits = need32Bits;
  13352. return vbo;
  13353. };
  13354. /**
  13355. * Bind a webGL buffer to the webGL context
  13356. * @param buffer defines the buffer to bind
  13357. */
  13358. Engine.prototype.bindArrayBuffer = function (buffer) {
  13359. if (!this._vaoRecordInProgress) {
  13360. this._unbindVertexArrayObject();
  13361. }
  13362. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13363. };
  13364. /**
  13365. * Bind an uniform buffer to the current webGL context
  13366. * @param buffer defines the buffer to bind
  13367. */
  13368. Engine.prototype.bindUniformBuffer = function (buffer) {
  13369. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13370. };
  13371. /**
  13372. * Bind a buffer to the current webGL context at a given location
  13373. * @param buffer defines the buffer to bind
  13374. * @param location defines the index where to bind the buffer
  13375. */
  13376. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13377. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13378. };
  13379. /**
  13380. * Bind a specific block at a given index in a specific shader program
  13381. * @param shaderProgram defines the shader program
  13382. * @param blockName defines the block name
  13383. * @param index defines the index where to bind the block
  13384. */
  13385. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13386. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13387. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13388. };
  13389. ;
  13390. Engine.prototype.bindIndexBuffer = function (buffer) {
  13391. if (!this._vaoRecordInProgress) {
  13392. this._unbindVertexArrayObject();
  13393. }
  13394. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13395. };
  13396. Engine.prototype.bindBuffer = function (buffer, target) {
  13397. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13398. this._gl.bindBuffer(target, buffer);
  13399. this._currentBoundBuffer[target] = buffer;
  13400. }
  13401. };
  13402. /**
  13403. * update the bound buffer with the given data
  13404. * @param data defines the data to update
  13405. */
  13406. Engine.prototype.updateArrayBuffer = function (data) {
  13407. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13408. };
  13409. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13410. var pointer = this._currentBufferPointers[indx];
  13411. var changed = false;
  13412. if (!pointer.active) {
  13413. changed = true;
  13414. pointer.active = true;
  13415. pointer.index = indx;
  13416. pointer.size = size;
  13417. pointer.type = type;
  13418. pointer.normalized = normalized;
  13419. pointer.stride = stride;
  13420. pointer.offset = offset;
  13421. pointer.buffer = buffer;
  13422. }
  13423. else {
  13424. if (pointer.buffer !== buffer) {
  13425. pointer.buffer = buffer;
  13426. changed = true;
  13427. }
  13428. if (pointer.size !== size) {
  13429. pointer.size = size;
  13430. changed = true;
  13431. }
  13432. if (pointer.type !== type) {
  13433. pointer.type = type;
  13434. changed = true;
  13435. }
  13436. if (pointer.normalized !== normalized) {
  13437. pointer.normalized = normalized;
  13438. changed = true;
  13439. }
  13440. if (pointer.stride !== stride) {
  13441. pointer.stride = stride;
  13442. changed = true;
  13443. }
  13444. if (pointer.offset !== offset) {
  13445. pointer.offset = offset;
  13446. changed = true;
  13447. }
  13448. }
  13449. if (changed || this._vaoRecordInProgress) {
  13450. this.bindArrayBuffer(buffer);
  13451. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13452. }
  13453. };
  13454. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13455. if (indexBuffer == null) {
  13456. return;
  13457. }
  13458. if (this._cachedIndexBuffer !== indexBuffer) {
  13459. this._cachedIndexBuffer = indexBuffer;
  13460. this.bindIndexBuffer(indexBuffer);
  13461. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13462. }
  13463. };
  13464. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13465. var attributes = effect.getAttributesNames();
  13466. if (!this._vaoRecordInProgress) {
  13467. this._unbindVertexArrayObject();
  13468. }
  13469. this.unbindAllAttributes();
  13470. for (var index = 0; index < attributes.length; index++) {
  13471. var order = effect.getAttributeLocation(index);
  13472. if (order >= 0) {
  13473. var vertexBuffer = vertexBuffers[attributes[index]];
  13474. if (!vertexBuffer) {
  13475. continue;
  13476. }
  13477. this._gl.enableVertexAttribArray(order);
  13478. if (!this._vaoRecordInProgress) {
  13479. this._vertexAttribArraysEnabled[order] = true;
  13480. }
  13481. var buffer = vertexBuffer.getBuffer();
  13482. if (buffer) {
  13483. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13484. if (vertexBuffer.getIsInstanced()) {
  13485. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13486. if (!this._vaoRecordInProgress) {
  13487. this._currentInstanceLocations.push(order);
  13488. this._currentInstanceBuffers.push(buffer);
  13489. }
  13490. }
  13491. }
  13492. }
  13493. }
  13494. };
  13495. /**
  13496. * Records a vertex array object
  13497. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13498. * @param vertexBuffers defines the list of vertex buffers to store
  13499. * @param indexBuffer defines the index buffer to store
  13500. * @param effect defines the effect to store
  13501. * @returns the new vertex array object
  13502. */
  13503. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13504. var vao = this._gl.createVertexArray();
  13505. this._vaoRecordInProgress = true;
  13506. this._gl.bindVertexArray(vao);
  13507. this._mustWipeVertexAttributes = true;
  13508. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13509. this.bindIndexBuffer(indexBuffer);
  13510. this._vaoRecordInProgress = false;
  13511. this._gl.bindVertexArray(null);
  13512. return vao;
  13513. };
  13514. /**
  13515. * Bind a specific vertex array object
  13516. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13517. * @param vertexArrayObject defines the vertex array object to bind
  13518. * @param indexBuffer defines the index buffer to bind
  13519. */
  13520. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13521. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13522. this._cachedVertexArrayObject = vertexArrayObject;
  13523. this._gl.bindVertexArray(vertexArrayObject);
  13524. this._cachedVertexBuffers = null;
  13525. this._cachedIndexBuffer = null;
  13526. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13527. this._mustWipeVertexAttributes = true;
  13528. }
  13529. };
  13530. /**
  13531. * Bind webGl buffers directly to the webGL context
  13532. * @param vertexBuffer defines the vertex buffer to bind
  13533. * @param indexBuffer defines the index buffer to bind
  13534. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13535. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13536. * @param effect defines the effect associated with the vertex buffer
  13537. */
  13538. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13539. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13540. this._cachedVertexBuffers = vertexBuffer;
  13541. this._cachedEffectForVertexBuffers = effect;
  13542. var attributesCount = effect.getAttributesCount();
  13543. this._unbindVertexArrayObject();
  13544. this.unbindAllAttributes();
  13545. var offset = 0;
  13546. for (var index = 0; index < attributesCount; index++) {
  13547. if (index < vertexDeclaration.length) {
  13548. var order = effect.getAttributeLocation(index);
  13549. if (order >= 0) {
  13550. this._gl.enableVertexAttribArray(order);
  13551. this._vertexAttribArraysEnabled[order] = true;
  13552. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13553. }
  13554. offset += vertexDeclaration[index] * 4;
  13555. }
  13556. }
  13557. }
  13558. this._bindIndexBufferWithCache(indexBuffer);
  13559. };
  13560. Engine.prototype._unbindVertexArrayObject = function () {
  13561. if (!this._cachedVertexArrayObject) {
  13562. return;
  13563. }
  13564. this._cachedVertexArrayObject = null;
  13565. this._gl.bindVertexArray(null);
  13566. };
  13567. /**
  13568. * Bind a list of vertex buffers to the webGL context
  13569. * @param vertexBuffers defines the list of vertex buffers to bind
  13570. * @param indexBuffer defines the index buffer to bind
  13571. * @param effect defines the effect associated with the vertex buffers
  13572. */
  13573. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13574. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13575. this._cachedVertexBuffers = vertexBuffers;
  13576. this._cachedEffectForVertexBuffers = effect;
  13577. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13578. }
  13579. this._bindIndexBufferWithCache(indexBuffer);
  13580. };
  13581. /**
  13582. * Unbind all instance attributes
  13583. */
  13584. Engine.prototype.unbindInstanceAttributes = function () {
  13585. var boundBuffer;
  13586. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13587. var instancesBuffer = this._currentInstanceBuffers[i];
  13588. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13589. boundBuffer = instancesBuffer;
  13590. this.bindArrayBuffer(instancesBuffer);
  13591. }
  13592. var offsetLocation = this._currentInstanceLocations[i];
  13593. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13594. }
  13595. this._currentInstanceBuffers.length = 0;
  13596. this._currentInstanceLocations.length = 0;
  13597. };
  13598. /**
  13599. * Release and free the memory of a vertex array object
  13600. * @param vao defines the vertex array object to delete
  13601. */
  13602. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13603. this._gl.deleteVertexArray(vao);
  13604. };
  13605. /** @hidden */
  13606. Engine.prototype._releaseBuffer = function (buffer) {
  13607. buffer.references--;
  13608. if (buffer.references === 0) {
  13609. this._gl.deleteBuffer(buffer);
  13610. return true;
  13611. }
  13612. return false;
  13613. };
  13614. /**
  13615. * Creates a webGL buffer to use with instanciation
  13616. * @param capacity defines the size of the buffer
  13617. * @returns the webGL buffer
  13618. */
  13619. Engine.prototype.createInstancesBuffer = function (capacity) {
  13620. var buffer = this._gl.createBuffer();
  13621. if (!buffer) {
  13622. throw new Error("Unable to create instance buffer");
  13623. }
  13624. buffer.capacity = capacity;
  13625. this.bindArrayBuffer(buffer);
  13626. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13627. return buffer;
  13628. };
  13629. /**
  13630. * Delete a webGL buffer used with instanciation
  13631. * @param buffer defines the webGL buffer to delete
  13632. */
  13633. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13634. this._gl.deleteBuffer(buffer);
  13635. };
  13636. /**
  13637. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13638. * @param instancesBuffer defines the webGL buffer to update and bind
  13639. * @param data defines the data to store in the buffer
  13640. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13641. */
  13642. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13643. this.bindArrayBuffer(instancesBuffer);
  13644. if (data) {
  13645. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13646. }
  13647. if (offsetLocations[0].index !== undefined) {
  13648. var stride = 0;
  13649. for (var i = 0; i < offsetLocations.length; i++) {
  13650. var ai = offsetLocations[i];
  13651. stride += ai.attributeSize * 4;
  13652. }
  13653. for (var i = 0; i < offsetLocations.length; i++) {
  13654. var ai = offsetLocations[i];
  13655. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13656. this._gl.enableVertexAttribArray(ai.index);
  13657. this._vertexAttribArraysEnabled[ai.index] = true;
  13658. }
  13659. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13660. this._gl.vertexAttribDivisor(ai.index, 1);
  13661. this._currentInstanceLocations.push(ai.index);
  13662. this._currentInstanceBuffers.push(instancesBuffer);
  13663. }
  13664. }
  13665. else {
  13666. for (var index = 0; index < 4; index++) {
  13667. var offsetLocation = offsetLocations[index];
  13668. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13669. this._gl.enableVertexAttribArray(offsetLocation);
  13670. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13671. }
  13672. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13673. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13674. this._currentInstanceLocations.push(offsetLocation);
  13675. this._currentInstanceBuffers.push(instancesBuffer);
  13676. }
  13677. }
  13678. };
  13679. /**
  13680. * Apply all cached states (depth, culling, stencil and alpha)
  13681. */
  13682. Engine.prototype.applyStates = function () {
  13683. this._depthCullingState.apply(this._gl);
  13684. this._stencilState.apply(this._gl);
  13685. this._alphaState.apply(this._gl);
  13686. };
  13687. /**
  13688. * Send a draw order
  13689. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13690. * @param indexStart defines the starting index
  13691. * @param indexCount defines the number of index to draw
  13692. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13693. */
  13694. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13695. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13696. };
  13697. /**
  13698. * Draw a list of points
  13699. * @param verticesStart defines the index of first vertex to draw
  13700. * @param verticesCount defines the count of vertices to draw
  13701. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13702. */
  13703. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13704. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13705. };
  13706. /**
  13707. * Draw a list of unindexed primitives
  13708. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13709. * @param verticesStart defines the index of first vertex to draw
  13710. * @param verticesCount defines the count of vertices to draw
  13711. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13712. */
  13713. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13714. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13715. };
  13716. /**
  13717. * Draw a list of indexed primitives
  13718. * @param fillMode defines the primitive to use
  13719. * @param indexStart defines the starting index
  13720. * @param indexCount defines the number of index to draw
  13721. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13722. */
  13723. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13724. // Apply states
  13725. this.applyStates();
  13726. this._drawCalls.addCount(1, false);
  13727. // Render
  13728. var drawMode = this._drawMode(fillMode);
  13729. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13730. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13731. if (instancesCount) {
  13732. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13733. }
  13734. else {
  13735. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13736. }
  13737. };
  13738. /**
  13739. * Draw a list of unindexed primitives
  13740. * @param fillMode defines the primitive to use
  13741. * @param verticesStart defines the index of first vertex to draw
  13742. * @param verticesCount defines the count of vertices to draw
  13743. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13744. */
  13745. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13746. // Apply states
  13747. this.applyStates();
  13748. this._drawCalls.addCount(1, false);
  13749. var drawMode = this._drawMode(fillMode);
  13750. if (instancesCount) {
  13751. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13752. }
  13753. else {
  13754. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13755. }
  13756. };
  13757. Engine.prototype._drawMode = function (fillMode) {
  13758. switch (fillMode) {
  13759. // Triangle views
  13760. case BABYLON.Material.TriangleFillMode:
  13761. return this._gl.TRIANGLES;
  13762. case BABYLON.Material.PointFillMode:
  13763. return this._gl.POINTS;
  13764. case BABYLON.Material.WireFrameFillMode:
  13765. return this._gl.LINES;
  13766. // Draw modes
  13767. case BABYLON.Material.PointListDrawMode:
  13768. return this._gl.POINTS;
  13769. case BABYLON.Material.LineListDrawMode:
  13770. return this._gl.LINES;
  13771. case BABYLON.Material.LineLoopDrawMode:
  13772. return this._gl.LINE_LOOP;
  13773. case BABYLON.Material.LineStripDrawMode:
  13774. return this._gl.LINE_STRIP;
  13775. case BABYLON.Material.TriangleStripDrawMode:
  13776. return this._gl.TRIANGLE_STRIP;
  13777. case BABYLON.Material.TriangleFanDrawMode:
  13778. return this._gl.TRIANGLE_FAN;
  13779. default:
  13780. return this._gl.TRIANGLES;
  13781. }
  13782. };
  13783. // Shaders
  13784. /** @hidden */
  13785. Engine.prototype._releaseEffect = function (effect) {
  13786. if (this._compiledEffects[effect._key]) {
  13787. delete this._compiledEffects[effect._key];
  13788. this._deleteProgram(effect.getProgram());
  13789. }
  13790. };
  13791. /** @hidden */
  13792. Engine.prototype._deleteProgram = function (program) {
  13793. if (program) {
  13794. program.__SPECTOR_rebuildProgram = null;
  13795. if (program.transformFeedback) {
  13796. this.deleteTransformFeedback(program.transformFeedback);
  13797. program.transformFeedback = null;
  13798. }
  13799. this._gl.deleteProgram(program);
  13800. }
  13801. };
  13802. /**
  13803. * Create a new effect (used to store vertex/fragment shaders)
  13804. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13805. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13806. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13807. * @param samplers defines an array of string used to represent textures
  13808. * @param defines defines the string containing the defines to use to compile the shaders
  13809. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13810. * @param onCompiled defines a function to call when the effect creation is successful
  13811. * @param onError defines a function to call when the effect creation has failed
  13812. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13813. * @returns the new Effect
  13814. */
  13815. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13816. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13817. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13818. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13819. if (this._compiledEffects[name]) {
  13820. var compiledEffect = this._compiledEffects[name];
  13821. if (onCompiled && compiledEffect.isReady()) {
  13822. onCompiled(compiledEffect);
  13823. }
  13824. return compiledEffect;
  13825. }
  13826. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13827. effect._key = name;
  13828. this._compiledEffects[name] = effect;
  13829. return effect;
  13830. };
  13831. /**
  13832. * Create an effect to use with particle systems
  13833. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13834. * @param uniformsNames defines a list of attribute names
  13835. * @param samplers defines an array of string used to represent textures
  13836. * @param defines defines the string containing the defines to use to compile the shaders
  13837. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13838. * @param onCompiled defines a function to call when the effect creation is successful
  13839. * @param onError defines a function to call when the effect creation has failed
  13840. * @returns the new Effect
  13841. */
  13842. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13843. if (uniformsNames === void 0) { uniformsNames = []; }
  13844. if (samplers === void 0) { samplers = []; }
  13845. if (defines === void 0) { defines = ""; }
  13846. return this.createEffect({
  13847. vertex: "particles",
  13848. fragmentElement: fragmentName
  13849. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13850. };
  13851. /**
  13852. * Directly creates a webGL program
  13853. * @param vertexCode defines the vertex shader code to use
  13854. * @param fragmentCode defines the fragment shader code to use
  13855. * @param context defines the webGL context to use (if not set, the current one will be used)
  13856. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13857. * @returns the new webGL program
  13858. */
  13859. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13860. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13861. context = context || this._gl;
  13862. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13863. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13864. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13865. };
  13866. /**
  13867. * Creates a webGL program
  13868. * @param vertexCode defines the vertex shader code to use
  13869. * @param fragmentCode defines the fragment shader code to use
  13870. * @param defines defines the string containing the defines to use to compile the shaders
  13871. * @param context defines the webGL context to use (if not set, the current one will be used)
  13872. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13873. * @returns the new webGL program
  13874. */
  13875. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13876. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13877. context = context || this._gl;
  13878. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13879. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13880. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13881. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13882. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13883. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13884. return program;
  13885. };
  13886. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13887. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13888. var shaderProgram = context.createProgram();
  13889. if (!shaderProgram) {
  13890. throw new Error("Unable to create program");
  13891. }
  13892. context.attachShader(shaderProgram, vertexShader);
  13893. context.attachShader(shaderProgram, fragmentShader);
  13894. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13895. var transformFeedback = this.createTransformFeedback();
  13896. this.bindTransformFeedback(transformFeedback);
  13897. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13898. shaderProgram.transformFeedback = transformFeedback;
  13899. }
  13900. context.linkProgram(shaderProgram);
  13901. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13902. this.bindTransformFeedback(null);
  13903. }
  13904. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13905. if (!linked) {
  13906. context.validateProgram(shaderProgram);
  13907. var error = context.getProgramInfoLog(shaderProgram);
  13908. if (error) {
  13909. throw new Error(error);
  13910. }
  13911. }
  13912. context.deleteShader(vertexShader);
  13913. context.deleteShader(fragmentShader);
  13914. return shaderProgram;
  13915. };
  13916. /**
  13917. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13918. * @param shaderProgram defines the webGL program to use
  13919. * @param uniformsNames defines the list of uniform names
  13920. * @returns an array of webGL uniform locations
  13921. */
  13922. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13923. var results = new Array();
  13924. for (var index = 0; index < uniformsNames.length; index++) {
  13925. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13926. }
  13927. return results;
  13928. };
  13929. /**
  13930. * Gets the lsit of active attributes for a given webGL program
  13931. * @param shaderProgram defines the webGL program to use
  13932. * @param attributesNames defines the list of attribute names to get
  13933. * @returns an array of indices indicating the offset of each attribute
  13934. */
  13935. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13936. var results = [];
  13937. for (var index = 0; index < attributesNames.length; index++) {
  13938. try {
  13939. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13940. }
  13941. catch (e) {
  13942. results.push(-1);
  13943. }
  13944. }
  13945. return results;
  13946. };
  13947. /**
  13948. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13949. * @param effect defines the effect to activate
  13950. */
  13951. Engine.prototype.enableEffect = function (effect) {
  13952. if (!effect) {
  13953. return;
  13954. }
  13955. // Use program
  13956. this.bindSamplers(effect);
  13957. this._currentEffect = effect;
  13958. if (effect.onBind) {
  13959. effect.onBind(effect);
  13960. }
  13961. effect.onBindObservable.notifyObservers(effect);
  13962. };
  13963. /**
  13964. * Set the value of an uniform to an array of int32
  13965. * @param uniform defines the webGL uniform location where to store the value
  13966. * @param array defines the array of int32 to store
  13967. */
  13968. Engine.prototype.setIntArray = function (uniform, array) {
  13969. if (!uniform)
  13970. return;
  13971. this._gl.uniform1iv(uniform, array);
  13972. };
  13973. /**
  13974. * Set the value of an uniform to an array of int32 (stored as vec2)
  13975. * @param uniform defines the webGL uniform location where to store the value
  13976. * @param array defines the array of int32 to store
  13977. */
  13978. Engine.prototype.setIntArray2 = function (uniform, array) {
  13979. if (!uniform || array.length % 2 !== 0)
  13980. return;
  13981. this._gl.uniform2iv(uniform, array);
  13982. };
  13983. /**
  13984. * Set the value of an uniform to an array of int32 (stored as vec3)
  13985. * @param uniform defines the webGL uniform location where to store the value
  13986. * @param array defines the array of int32 to store
  13987. */
  13988. Engine.prototype.setIntArray3 = function (uniform, array) {
  13989. if (!uniform || array.length % 3 !== 0)
  13990. return;
  13991. this._gl.uniform3iv(uniform, array);
  13992. };
  13993. /**
  13994. * Set the value of an uniform to an array of int32 (stored as vec4)
  13995. * @param uniform defines the webGL uniform location where to store the value
  13996. * @param array defines the array of int32 to store
  13997. */
  13998. Engine.prototype.setIntArray4 = function (uniform, array) {
  13999. if (!uniform || array.length % 4 !== 0)
  14000. return;
  14001. this._gl.uniform4iv(uniform, array);
  14002. };
  14003. /**
  14004. * Set the value of an uniform to an array of float32
  14005. * @param uniform defines the webGL uniform location where to store the value
  14006. * @param array defines the array of float32 to store
  14007. */
  14008. Engine.prototype.setFloatArray = function (uniform, array) {
  14009. if (!uniform)
  14010. return;
  14011. this._gl.uniform1fv(uniform, array);
  14012. };
  14013. /**
  14014. * Set the value of an uniform to an array of float32 (stored as vec2)
  14015. * @param uniform defines the webGL uniform location where to store the value
  14016. * @param array defines the array of float32 to store
  14017. */
  14018. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14019. if (!uniform || array.length % 2 !== 0)
  14020. return;
  14021. this._gl.uniform2fv(uniform, array);
  14022. };
  14023. /**
  14024. * Set the value of an uniform to an array of float32 (stored as vec3)
  14025. * @param uniform defines the webGL uniform location where to store the value
  14026. * @param array defines the array of float32 to store
  14027. */
  14028. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14029. if (!uniform || array.length % 3 !== 0)
  14030. return;
  14031. this._gl.uniform3fv(uniform, array);
  14032. };
  14033. /**
  14034. * Set the value of an uniform to an array of float32 (stored as vec4)
  14035. * @param uniform defines the webGL uniform location where to store the value
  14036. * @param array defines the array of float32 to store
  14037. */
  14038. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14039. if (!uniform || array.length % 4 !== 0)
  14040. return;
  14041. this._gl.uniform4fv(uniform, array);
  14042. };
  14043. /**
  14044. * Set the value of an uniform to an array of number
  14045. * @param uniform defines the webGL uniform location where to store the value
  14046. * @param array defines the array of number to store
  14047. */
  14048. Engine.prototype.setArray = function (uniform, array) {
  14049. if (!uniform)
  14050. return;
  14051. this._gl.uniform1fv(uniform, array);
  14052. };
  14053. /**
  14054. * Set the value of an uniform to an array of number (stored as vec2)
  14055. * @param uniform defines the webGL uniform location where to store the value
  14056. * @param array defines the array of number to store
  14057. */
  14058. Engine.prototype.setArray2 = function (uniform, array) {
  14059. if (!uniform || array.length % 2 !== 0)
  14060. return;
  14061. this._gl.uniform2fv(uniform, array);
  14062. };
  14063. /**
  14064. * Set the value of an uniform to an array of number (stored as vec3)
  14065. * @param uniform defines the webGL uniform location where to store the value
  14066. * @param array defines the array of number to store
  14067. */
  14068. Engine.prototype.setArray3 = function (uniform, array) {
  14069. if (!uniform || array.length % 3 !== 0)
  14070. return;
  14071. this._gl.uniform3fv(uniform, array);
  14072. };
  14073. /**
  14074. * Set the value of an uniform to an array of number (stored as vec4)
  14075. * @param uniform defines the webGL uniform location where to store the value
  14076. * @param array defines the array of number to store
  14077. */
  14078. Engine.prototype.setArray4 = function (uniform, array) {
  14079. if (!uniform || array.length % 4 !== 0)
  14080. return;
  14081. this._gl.uniform4fv(uniform, array);
  14082. };
  14083. /**
  14084. * Set the value of an uniform to an array of float32 (stored as matrices)
  14085. * @param uniform defines the webGL uniform location where to store the value
  14086. * @param matrices defines the array of float32 to store
  14087. */
  14088. Engine.prototype.setMatrices = function (uniform, matrices) {
  14089. if (!uniform)
  14090. return;
  14091. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14092. };
  14093. /**
  14094. * Set the value of an uniform to a matrix
  14095. * @param uniform defines the webGL uniform location where to store the value
  14096. * @param matrix defines the matrix to store
  14097. */
  14098. Engine.prototype.setMatrix = function (uniform, matrix) {
  14099. if (!uniform)
  14100. return;
  14101. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14102. };
  14103. /**
  14104. * Set the value of an uniform to a matrix (3x3)
  14105. * @param uniform defines the webGL uniform location where to store the value
  14106. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14107. */
  14108. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14109. if (!uniform)
  14110. return;
  14111. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14112. };
  14113. /**
  14114. * Set the value of an uniform to a matrix (2x2)
  14115. * @param uniform defines the webGL uniform location where to store the value
  14116. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14117. */
  14118. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14119. if (!uniform)
  14120. return;
  14121. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14122. };
  14123. /**
  14124. * Set the value of an uniform to a number (int)
  14125. * @param uniform defines the webGL uniform location where to store the value
  14126. * @param value defines the int number to store
  14127. */
  14128. Engine.prototype.setInt = function (uniform, value) {
  14129. if (!uniform)
  14130. return;
  14131. this._gl.uniform1i(uniform, value);
  14132. };
  14133. /**
  14134. * Set the value of an uniform to a number (float)
  14135. * @param uniform defines the webGL uniform location where to store the value
  14136. * @param value defines the float number to store
  14137. */
  14138. Engine.prototype.setFloat = function (uniform, value) {
  14139. if (!uniform)
  14140. return;
  14141. this._gl.uniform1f(uniform, value);
  14142. };
  14143. /**
  14144. * Set the value of an uniform to a vec2
  14145. * @param uniform defines the webGL uniform location where to store the value
  14146. * @param x defines the 1st component of the value
  14147. * @param y defines the 2nd component of the value
  14148. */
  14149. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14150. if (!uniform)
  14151. return;
  14152. this._gl.uniform2f(uniform, x, y);
  14153. };
  14154. /**
  14155. * Set the value of an uniform to a vec3
  14156. * @param uniform defines the webGL uniform location where to store the value
  14157. * @param x defines the 1st component of the value
  14158. * @param y defines the 2nd component of the value
  14159. * @param z defines the 3rd component of the value
  14160. */
  14161. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14162. if (!uniform)
  14163. return;
  14164. this._gl.uniform3f(uniform, x, y, z);
  14165. };
  14166. /**
  14167. * Set the value of an uniform to a boolean
  14168. * @param uniform defines the webGL uniform location where to store the value
  14169. * @param bool defines the boolean to store
  14170. */
  14171. Engine.prototype.setBool = function (uniform, bool) {
  14172. if (!uniform)
  14173. return;
  14174. this._gl.uniform1i(uniform, bool);
  14175. };
  14176. /**
  14177. * Set the value of an uniform to a vec4
  14178. * @param uniform defines the webGL uniform location where to store the value
  14179. * @param x defines the 1st component of the value
  14180. * @param y defines the 2nd component of the value
  14181. * @param z defines the 3rd component of the value
  14182. * @param w defines the 4th component of the value
  14183. */
  14184. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14185. if (!uniform)
  14186. return;
  14187. this._gl.uniform4f(uniform, x, y, z, w);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to a Color3
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param color3 defines the color to store
  14193. */
  14194. Engine.prototype.setColor3 = function (uniform, color3) {
  14195. if (!uniform)
  14196. return;
  14197. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14198. };
  14199. /**
  14200. * Set the value of an uniform to a Color3 and an alpha value
  14201. * @param uniform defines the webGL uniform location where to store the value
  14202. * @param color3 defines the color to store
  14203. * @param alpha defines the alpha component to store
  14204. */
  14205. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14206. if (!uniform)
  14207. return;
  14208. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14209. };
  14210. /**
  14211. * Sets a Color4 on a uniform variable
  14212. * @param uniform defines the uniform location
  14213. * @param color4 defines the value to be set
  14214. */
  14215. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14216. if (!uniform)
  14217. return;
  14218. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14219. };
  14220. // States
  14221. /**
  14222. * Set various states to the webGL context
  14223. * @param culling defines backface culling state
  14224. * @param zOffset defines the value to apply to zOffset (0 by default)
  14225. * @param force defines if states must be applied even if cache is up to date
  14226. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14227. */
  14228. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14229. if (zOffset === void 0) { zOffset = 0; }
  14230. if (reverseSide === void 0) { reverseSide = false; }
  14231. // Culling
  14232. if (this._depthCullingState.cull !== culling || force) {
  14233. this._depthCullingState.cull = culling;
  14234. }
  14235. // Cull face
  14236. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14237. if (this._depthCullingState.cullFace !== cullFace || force) {
  14238. this._depthCullingState.cullFace = cullFace;
  14239. }
  14240. // Z offset
  14241. this.setZOffset(zOffset);
  14242. // Front face
  14243. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14244. if (this._depthCullingState.frontFace !== frontFace || force) {
  14245. this._depthCullingState.frontFace = frontFace;
  14246. }
  14247. };
  14248. /**
  14249. * Set the z offset to apply to current rendering
  14250. * @param value defines the offset to apply
  14251. */
  14252. Engine.prototype.setZOffset = function (value) {
  14253. this._depthCullingState.zOffset = value;
  14254. };
  14255. /**
  14256. * Gets the current value of the zOffset
  14257. * @returns the current zOffset state
  14258. */
  14259. Engine.prototype.getZOffset = function () {
  14260. return this._depthCullingState.zOffset;
  14261. };
  14262. /**
  14263. * Enable or disable depth buffering
  14264. * @param enable defines the state to set
  14265. */
  14266. Engine.prototype.setDepthBuffer = function (enable) {
  14267. this._depthCullingState.depthTest = enable;
  14268. };
  14269. /**
  14270. * Gets a boolean indicating if depth writing is enabled
  14271. * @returns the current depth writing state
  14272. */
  14273. Engine.prototype.getDepthWrite = function () {
  14274. return this._depthCullingState.depthMask;
  14275. };
  14276. /**
  14277. * Enable or disable depth writing
  14278. * @param enable defines the state to set
  14279. */
  14280. Engine.prototype.setDepthWrite = function (enable) {
  14281. this._depthCullingState.depthMask = enable;
  14282. };
  14283. /**
  14284. * Enable or disable color writing
  14285. * @param enable defines the state to set
  14286. */
  14287. Engine.prototype.setColorWrite = function (enable) {
  14288. this._gl.colorMask(enable, enable, enable, enable);
  14289. this._colorWrite = enable;
  14290. };
  14291. /**
  14292. * Gets a boolean indicating if color writing is enabled
  14293. * @returns the current color writing state
  14294. */
  14295. Engine.prototype.getColorWrite = function () {
  14296. return this._colorWrite;
  14297. };
  14298. /**
  14299. * Sets alpha constants used by some alpha blending modes
  14300. * @param r defines the red component
  14301. * @param g defines the green component
  14302. * @param b defines the blue component
  14303. * @param a defines the alpha component
  14304. */
  14305. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14306. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14307. };
  14308. /**
  14309. * Sets the current alpha mode
  14310. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14311. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14312. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14313. */
  14314. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14315. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14316. if (this._alphaMode === mode) {
  14317. return;
  14318. }
  14319. switch (mode) {
  14320. case Engine.ALPHA_DISABLE:
  14321. this._alphaState.alphaBlend = false;
  14322. break;
  14323. case Engine.ALPHA_PREMULTIPLIED:
  14324. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14325. this._alphaState.alphaBlend = true;
  14326. break;
  14327. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14328. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14329. this._alphaState.alphaBlend = true;
  14330. break;
  14331. case Engine.ALPHA_COMBINE:
  14332. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14333. this._alphaState.alphaBlend = true;
  14334. break;
  14335. case Engine.ALPHA_ONEONE:
  14336. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14337. this._alphaState.alphaBlend = true;
  14338. break;
  14339. case Engine.ALPHA_ADD:
  14340. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14341. this._alphaState.alphaBlend = true;
  14342. break;
  14343. case Engine.ALPHA_SUBTRACT:
  14344. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14345. this._alphaState.alphaBlend = true;
  14346. break;
  14347. case Engine.ALPHA_MULTIPLY:
  14348. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14349. this._alphaState.alphaBlend = true;
  14350. break;
  14351. case Engine.ALPHA_MAXIMIZED:
  14352. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14353. this._alphaState.alphaBlend = true;
  14354. break;
  14355. case Engine.ALPHA_INTERPOLATE:
  14356. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14357. this._alphaState.alphaBlend = true;
  14358. break;
  14359. case Engine.ALPHA_SCREENMODE:
  14360. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14361. this._alphaState.alphaBlend = true;
  14362. break;
  14363. }
  14364. if (!noDepthWriteChange) {
  14365. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14366. }
  14367. this._alphaMode = mode;
  14368. };
  14369. /**
  14370. * Gets the current alpha mode
  14371. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14372. * @returns the current alpha mode
  14373. */
  14374. Engine.prototype.getAlphaMode = function () {
  14375. return this._alphaMode;
  14376. };
  14377. // Textures
  14378. /**
  14379. * Force the entire cache to be cleared
  14380. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14381. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14382. */
  14383. Engine.prototype.wipeCaches = function (bruteForce) {
  14384. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14385. return;
  14386. }
  14387. this._currentEffect = null;
  14388. if (bruteForce) {
  14389. this.resetTextureCache();
  14390. this._currentProgram = null;
  14391. this._stencilState.reset();
  14392. this._depthCullingState.reset();
  14393. this.setDepthFunctionToLessOrEqual();
  14394. this._alphaState.reset();
  14395. }
  14396. this._resetVertexBufferBinding();
  14397. this._cachedIndexBuffer = null;
  14398. this._cachedEffectForVertexBuffers = null;
  14399. this._unbindVertexArrayObject();
  14400. this.bindIndexBuffer(null);
  14401. };
  14402. /**
  14403. * Set the compressed texture format to use, based on the formats you have, and the formats
  14404. * supported by the hardware / browser.
  14405. *
  14406. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14407. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14408. * to API arguments needed to compressed textures. This puts the burden on the container
  14409. * generator to house the arcane code for determining these for current & future formats.
  14410. *
  14411. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14412. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14413. *
  14414. * Note: The result of this call is not taken into account when a texture is base64.
  14415. *
  14416. * @param formatsAvailable defines the list of those format families you have created
  14417. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14418. *
  14419. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14420. * @returns The extension selected.
  14421. */
  14422. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14423. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14424. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14425. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14426. return this._textureFormatInUse = this._texturesSupported[i];
  14427. }
  14428. }
  14429. }
  14430. // actively set format to nothing, to allow this to be called more than once
  14431. // and possibly fail the 2nd time
  14432. this._textureFormatInUse = null;
  14433. return null;
  14434. };
  14435. /** @hidden */
  14436. Engine.prototype._createTexture = function () {
  14437. var texture = this._gl.createTexture();
  14438. if (!texture) {
  14439. throw new Error("Unable to create texture");
  14440. }
  14441. return texture;
  14442. };
  14443. /**
  14444. * Usually called from BABYLON.Texture.ts.
  14445. * Passed information to create a WebGLTexture
  14446. * @param urlArg defines a value which contains one of the following:
  14447. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14448. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14449. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14450. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14451. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14452. * @param scene needed for loading to the correct scene
  14453. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14454. * @param onLoad optional callback to be called upon successful completion
  14455. * @param onError optional callback to be called upon failure
  14456. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14457. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14458. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14459. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14460. */
  14461. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14462. var _this = this;
  14463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14464. if (onLoad === void 0) { onLoad = null; }
  14465. if (onError === void 0) { onError = null; }
  14466. if (buffer === void 0) { buffer = null; }
  14467. if (fallback === void 0) { fallback = null; }
  14468. if (format === void 0) { format = null; }
  14469. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14470. var fromData = url.substr(0, 5) === "data:";
  14471. var fromBlob = url.substr(0, 5) === "blob:";
  14472. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14473. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14474. // establish the file extension, if possible
  14475. var lastDot = url.lastIndexOf('.');
  14476. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14477. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14478. var isTGA = (extension.indexOf(".tga") === 0);
  14479. // determine if a ktx file should be substituted
  14480. var isKTX = false;
  14481. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14482. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14483. isKTX = true;
  14484. }
  14485. if (scene) {
  14486. scene._addPendingData(texture);
  14487. }
  14488. texture.url = url;
  14489. texture.generateMipMaps = !noMipmap;
  14490. texture.samplingMode = samplingMode;
  14491. texture.invertY = invertY;
  14492. if (!this._doNotHandleContextLost) {
  14493. // Keep a link to the buffer only if we plan to handle context lost
  14494. texture._buffer = buffer;
  14495. }
  14496. var onLoadObserver = null;
  14497. if (onLoad && !fallback) {
  14498. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14499. }
  14500. if (!fallback)
  14501. this._internalTexturesCache.push(texture);
  14502. var onerror = function (message, exception) {
  14503. if (scene) {
  14504. scene._removePendingData(texture);
  14505. }
  14506. if (onLoadObserver) {
  14507. texture.onLoadedObservable.remove(onLoadObserver);
  14508. }
  14509. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14510. if (isKTX) {
  14511. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14512. }
  14513. else if (BABYLON.Tools.UseFallbackTexture) {
  14514. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14515. }
  14516. if (onError) {
  14517. onError(message || "Unknown error", exception);
  14518. }
  14519. };
  14520. var callback = null;
  14521. // processing for non-image formats
  14522. if (isKTX || isTGA || isDDS) {
  14523. if (isKTX) {
  14524. callback = function (data) {
  14525. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14526. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14527. ktx.uploadLevels(_this._gl, !noMipmap);
  14528. return false;
  14529. }, samplingMode);
  14530. };
  14531. }
  14532. else if (isTGA) {
  14533. callback = function (arrayBuffer) {
  14534. var data = new Uint8Array(arrayBuffer);
  14535. var header = BABYLON.TGATools.GetTGAHeader(data);
  14536. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14537. BABYLON.TGATools.UploadContent(_this._gl, data);
  14538. return false;
  14539. }, samplingMode);
  14540. };
  14541. }
  14542. else if (isDDS) {
  14543. callback = function (data) {
  14544. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14545. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14546. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14547. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14548. return false;
  14549. }, samplingMode);
  14550. };
  14551. }
  14552. if (!buffer) {
  14553. this._loadFile(url, function (data) {
  14554. if (callback) {
  14555. callback(data);
  14556. }
  14557. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14558. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14559. });
  14560. }
  14561. else {
  14562. if (callback) {
  14563. callback(buffer);
  14564. }
  14565. }
  14566. // image format processing
  14567. }
  14568. else {
  14569. var onload = function (img) {
  14570. if (fromBlob && !_this._doNotHandleContextLost) {
  14571. // We need to store the image if we need to rebuild the texture
  14572. // in case of a webgl context lost
  14573. texture._buffer = img;
  14574. }
  14575. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14576. var gl = _this._gl;
  14577. var isPot = (img.width === potWidth && img.height === potHeight);
  14578. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14579. if (isPot) {
  14580. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14581. return false;
  14582. }
  14583. // Using shaders to rescale because canvas.drawImage is lossy
  14584. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14585. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14586. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14587. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14588. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14589. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14590. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14591. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14592. _this._releaseTexture(source);
  14593. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14594. continuationCallback();
  14595. });
  14596. return true;
  14597. }, samplingMode);
  14598. };
  14599. if (!fromData || isBase64)
  14600. if (buffer instanceof HTMLImageElement) {
  14601. onload(buffer);
  14602. }
  14603. else {
  14604. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14605. }
  14606. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14607. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14608. else
  14609. onload(buffer);
  14610. }
  14611. return texture;
  14612. };
  14613. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14614. var _this = this;
  14615. var rtt = this.createRenderTargetTexture({
  14616. width: destination.width,
  14617. height: destination.height,
  14618. }, {
  14619. generateMipMaps: false,
  14620. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14621. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14622. generateDepthBuffer: false,
  14623. generateStencilBuffer: false
  14624. });
  14625. if (!this._rescalePostProcess) {
  14626. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14627. }
  14628. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14629. _this._rescalePostProcess.onApply = function (effect) {
  14630. effect._bindTexture("textureSampler", source);
  14631. };
  14632. var hostingScene = scene;
  14633. if (!hostingScene) {
  14634. hostingScene = _this.scenes[_this.scenes.length - 1];
  14635. }
  14636. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14637. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14638. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14639. _this.unBindFramebuffer(rtt);
  14640. _this._releaseTexture(rtt);
  14641. if (onComplete) {
  14642. onComplete();
  14643. }
  14644. });
  14645. };
  14646. /**
  14647. * Update a raw texture
  14648. * @param texture defines the texture to update
  14649. * @param data defines the data to store in the texture
  14650. * @param format defines the format of the data
  14651. * @param invertY defines if data must be stored with Y axis inverted
  14652. * @param compression defines the compression used (null by default)
  14653. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14654. */
  14655. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14656. if (compression === void 0) { compression = null; }
  14657. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14658. if (!texture) {
  14659. return;
  14660. }
  14661. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14662. var internalFormat = this._getInternalFormat(format);
  14663. var textureType = this._getWebGLTextureType(type);
  14664. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14665. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14666. if (!this._doNotHandleContextLost) {
  14667. texture._bufferView = data;
  14668. texture.format = format;
  14669. texture.type = type;
  14670. texture.invertY = invertY;
  14671. texture._compression = compression;
  14672. }
  14673. if (texture.width % 4 !== 0) {
  14674. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14675. }
  14676. if (compression && data) {
  14677. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14678. }
  14679. else {
  14680. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14681. }
  14682. if (texture.generateMipMaps) {
  14683. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14684. }
  14685. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14686. // this.resetTextureCache();
  14687. texture.isReady = true;
  14688. };
  14689. /**
  14690. * Creates a raw texture
  14691. * @param data defines the data to store in the texture
  14692. * @param width defines the width of the texture
  14693. * @param height defines the height of the texture
  14694. * @param format defines the format of the data
  14695. * @param generateMipMaps defines if the engine should generate the mip levels
  14696. * @param invertY defines if data must be stored with Y axis inverted
  14697. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14698. * @param compression defines the compression used (null by default)
  14699. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14700. * @returns the raw texture inside an InternalTexture
  14701. */
  14702. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14703. if (compression === void 0) { compression = null; }
  14704. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14705. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14706. texture.baseWidth = width;
  14707. texture.baseHeight = height;
  14708. texture.width = width;
  14709. texture.height = height;
  14710. texture.format = format;
  14711. texture.generateMipMaps = generateMipMaps;
  14712. texture.samplingMode = samplingMode;
  14713. texture.invertY = invertY;
  14714. texture._compression = compression;
  14715. texture.type = type;
  14716. if (!this._doNotHandleContextLost) {
  14717. texture._bufferView = data;
  14718. }
  14719. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14720. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14721. // Filters
  14722. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14723. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14724. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14725. if (generateMipMaps) {
  14726. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14727. }
  14728. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14729. this._internalTexturesCache.push(texture);
  14730. return texture;
  14731. };
  14732. /**
  14733. * Creates a dynamic texture
  14734. * @param width defines the width of the texture
  14735. * @param height defines the height of the texture
  14736. * @param generateMipMaps defines if the engine should generate the mip levels
  14737. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14738. * @returns the dynamic texture inside an InternalTexture
  14739. */
  14740. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14741. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14742. texture.baseWidth = width;
  14743. texture.baseHeight = height;
  14744. if (generateMipMaps) {
  14745. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14746. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14747. }
  14748. // this.resetTextureCache();
  14749. texture.width = width;
  14750. texture.height = height;
  14751. texture.isReady = false;
  14752. texture.generateMipMaps = generateMipMaps;
  14753. texture.samplingMode = samplingMode;
  14754. this.updateTextureSamplingMode(samplingMode, texture);
  14755. this._internalTexturesCache.push(texture);
  14756. return texture;
  14757. };
  14758. /**
  14759. * Update the sampling mode of a given texture
  14760. * @param samplingMode defines the required sampling mode
  14761. * @param texture defines the texture to update
  14762. */
  14763. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14764. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14765. if (texture.isCube) {
  14766. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14767. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14768. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14769. }
  14770. else if (texture.is3D) {
  14771. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14772. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14773. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14774. }
  14775. else {
  14776. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14777. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14778. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14779. }
  14780. texture.samplingMode = samplingMode;
  14781. };
  14782. /**
  14783. * Update the content of a dynamic texture
  14784. * @param texture defines the texture to update
  14785. * @param canvas defines the canvas containing the source
  14786. * @param invertY defines if data must be stored with Y axis inverted
  14787. * @param premulAlpha defines if alpha is stored as premultiplied
  14788. * @param format defines the format of the data
  14789. */
  14790. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14791. if (premulAlpha === void 0) { premulAlpha = false; }
  14792. if (!texture) {
  14793. return;
  14794. }
  14795. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14796. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14797. if (premulAlpha) {
  14798. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14799. }
  14800. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14801. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14802. if (texture.generateMipMaps) {
  14803. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14804. }
  14805. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14806. if (premulAlpha) {
  14807. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14808. }
  14809. texture.isReady = true;
  14810. };
  14811. /**
  14812. * Update a video texture
  14813. * @param texture defines the texture to update
  14814. * @param video defines the video element to use
  14815. * @param invertY defines if data must be stored with Y axis inverted
  14816. */
  14817. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14818. if (!texture || texture._isDisabled) {
  14819. return;
  14820. }
  14821. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14822. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14823. try {
  14824. // Testing video texture support
  14825. if (this._videoTextureSupported === undefined) {
  14826. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14827. if (this._gl.getError() !== 0) {
  14828. this._videoTextureSupported = false;
  14829. }
  14830. else {
  14831. this._videoTextureSupported = true;
  14832. }
  14833. }
  14834. // Copy video through the current working canvas if video texture is not supported
  14835. if (!this._videoTextureSupported) {
  14836. if (!texture._workingCanvas) {
  14837. texture._workingCanvas = document.createElement("canvas");
  14838. var context = texture._workingCanvas.getContext("2d");
  14839. if (!context) {
  14840. throw new Error("Unable to get 2d context");
  14841. }
  14842. texture._workingContext = context;
  14843. texture._workingCanvas.width = texture.width;
  14844. texture._workingCanvas.height = texture.height;
  14845. }
  14846. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14847. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14848. }
  14849. else {
  14850. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14851. }
  14852. if (texture.generateMipMaps) {
  14853. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14854. }
  14855. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14856. // this.resetTextureCache();
  14857. texture.isReady = true;
  14858. }
  14859. catch (ex) {
  14860. // Something unexpected
  14861. // Let's disable the texture
  14862. texture._isDisabled = true;
  14863. }
  14864. };
  14865. /**
  14866. * Updates a depth texture Comparison Mode and Function.
  14867. * If the comparison Function is equal to 0, the mode will be set to none.
  14868. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14869. * @param texture The texture to set the comparison function for
  14870. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14871. */
  14872. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14873. if (this.webGLVersion === 1) {
  14874. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14875. return;
  14876. }
  14877. var gl = this._gl;
  14878. if (texture.isCube) {
  14879. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14880. if (comparisonFunction === 0) {
  14881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14883. }
  14884. else {
  14885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14887. }
  14888. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14889. }
  14890. else {
  14891. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14892. if (comparisonFunction === 0) {
  14893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14895. }
  14896. else {
  14897. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14899. }
  14900. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14901. }
  14902. texture._comparisonFunction = comparisonFunction;
  14903. };
  14904. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14905. var width = size.width || size;
  14906. var height = size.height || size;
  14907. internalTexture.baseWidth = width;
  14908. internalTexture.baseHeight = height;
  14909. internalTexture.width = width;
  14910. internalTexture.height = height;
  14911. internalTexture.isReady = true;
  14912. internalTexture.samples = 1;
  14913. internalTexture.generateMipMaps = false;
  14914. internalTexture._generateDepthBuffer = true;
  14915. internalTexture._generateStencilBuffer = generateStencil;
  14916. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14917. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14918. internalTexture._comparisonFunction = comparisonFunction;
  14919. var gl = this._gl;
  14920. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14921. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14922. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14923. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14924. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14925. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14926. if (comparisonFunction === 0) {
  14927. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14928. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14929. }
  14930. else {
  14931. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14932. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14933. }
  14934. };
  14935. /**
  14936. * Creates a depth stencil texture.
  14937. * This is only available in WebGL 2 or with the depth texture extension available.
  14938. * @param size The size of face edge in the texture.
  14939. * @param options The options defining the texture.
  14940. * @returns The texture
  14941. */
  14942. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14943. if (options.isCube) {
  14944. var width = size.width || size;
  14945. return this._createDepthStencilCubeTexture(width, options);
  14946. }
  14947. else {
  14948. return this._createDepthStencilTexture(size, options);
  14949. }
  14950. };
  14951. /**
  14952. * Creates a depth stencil texture.
  14953. * This is only available in WebGL 2 or with the depth texture extension available.
  14954. * @param size The size of face edge in the texture.
  14955. * @param options The options defining the texture.
  14956. * @returns The texture
  14957. */
  14958. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14959. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14960. if (!this._caps.depthTextureExtension) {
  14961. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14962. return internalTexture;
  14963. }
  14964. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14965. var gl = this._gl;
  14966. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14967. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14968. if (this.webGLVersion > 1) {
  14969. if (internalOptions.generateStencil) {
  14970. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14971. }
  14972. else {
  14973. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14974. }
  14975. }
  14976. else {
  14977. if (internalOptions.generateStencil) {
  14978. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14979. }
  14980. else {
  14981. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14982. }
  14983. }
  14984. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14985. return internalTexture;
  14986. };
  14987. /**
  14988. * Creates a depth stencil cube texture.
  14989. * This is only available in WebGL 2.
  14990. * @param size The size of face edge in the cube texture.
  14991. * @param options The options defining the cube texture.
  14992. * @returns The cube texture
  14993. */
  14994. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14995. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14996. internalTexture.isCube = true;
  14997. if (this.webGLVersion === 1) {
  14998. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14999. return internalTexture;
  15000. }
  15001. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15002. var gl = this._gl;
  15003. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15004. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15005. // Create the depth/stencil buffer
  15006. for (var face = 0; face < 6; face++) {
  15007. if (internalOptions.generateStencil) {
  15008. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15009. }
  15010. else {
  15011. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15012. }
  15013. }
  15014. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15015. return internalTexture;
  15016. };
  15017. /**
  15018. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15019. * @param renderTarget The render target to set the frame buffer for
  15020. */
  15021. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15022. // Create the framebuffer
  15023. var internalTexture = renderTarget.getInternalTexture();
  15024. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15025. return;
  15026. }
  15027. var gl = this._gl;
  15028. var depthStencilTexture = renderTarget.depthStencilTexture;
  15029. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15030. if (depthStencilTexture.isCube) {
  15031. if (depthStencilTexture._generateStencilBuffer) {
  15032. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15033. }
  15034. else {
  15035. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15036. }
  15037. }
  15038. else {
  15039. if (depthStencilTexture._generateStencilBuffer) {
  15040. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15041. }
  15042. else {
  15043. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15044. }
  15045. }
  15046. this.bindUnboundFramebuffer(null);
  15047. };
  15048. /**
  15049. * Creates a new render target texture
  15050. * @param size defines the size of the texture
  15051. * @param options defines the options used to create the texture
  15052. * @returns a new render target texture stored in an InternalTexture
  15053. */
  15054. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15055. var fullOptions = new RenderTargetCreationOptions();
  15056. if (options !== undefined && typeof options === "object") {
  15057. fullOptions.generateMipMaps = options.generateMipMaps;
  15058. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15059. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15060. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15061. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15062. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15063. }
  15064. else {
  15065. fullOptions.generateMipMaps = options;
  15066. fullOptions.generateDepthBuffer = true;
  15067. fullOptions.generateStencilBuffer = false;
  15068. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15069. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15070. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15071. }
  15072. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15073. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15074. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15075. }
  15076. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15077. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15078. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15079. }
  15080. var gl = this._gl;
  15081. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15082. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15083. var width = size.width || size;
  15084. var height = size.height || size;
  15085. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15086. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15087. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15088. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15089. }
  15090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15094. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15095. // Create the framebuffer
  15096. var framebuffer = gl.createFramebuffer();
  15097. this.bindUnboundFramebuffer(framebuffer);
  15098. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15099. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15100. if (fullOptions.generateMipMaps) {
  15101. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15102. }
  15103. // Unbind
  15104. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15105. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15106. this.bindUnboundFramebuffer(null);
  15107. texture._framebuffer = framebuffer;
  15108. texture.baseWidth = width;
  15109. texture.baseHeight = height;
  15110. texture.width = width;
  15111. texture.height = height;
  15112. texture.isReady = true;
  15113. texture.samples = 1;
  15114. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15115. texture.samplingMode = fullOptions.samplingMode;
  15116. texture.type = fullOptions.type;
  15117. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15118. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15119. // this.resetTextureCache();
  15120. this._internalTexturesCache.push(texture);
  15121. return texture;
  15122. };
  15123. /**
  15124. * Create a multi render target texture
  15125. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15126. * @param size defines the size of the texture
  15127. * @param options defines the creation options
  15128. * @returns the cube texture as an InternalTexture
  15129. */
  15130. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15131. var generateMipMaps = false;
  15132. var generateDepthBuffer = true;
  15133. var generateStencilBuffer = false;
  15134. var generateDepthTexture = false;
  15135. var textureCount = 1;
  15136. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15137. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15138. var types = new Array();
  15139. var samplingModes = new Array();
  15140. if (options !== undefined) {
  15141. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15142. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15143. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15144. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15145. textureCount = options.textureCount || 1;
  15146. if (options.types) {
  15147. types = options.types;
  15148. }
  15149. if (options.samplingModes) {
  15150. samplingModes = options.samplingModes;
  15151. }
  15152. }
  15153. var gl = this._gl;
  15154. // Create the framebuffer
  15155. var framebuffer = gl.createFramebuffer();
  15156. this.bindUnboundFramebuffer(framebuffer);
  15157. var width = size.width || size;
  15158. var height = size.height || size;
  15159. var textures = [];
  15160. var attachments = [];
  15161. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15162. for (var i = 0; i < textureCount; i++) {
  15163. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15164. var type = types[i] || defaultType;
  15165. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15166. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15167. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15168. }
  15169. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15170. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15171. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15172. }
  15173. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15174. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15175. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15176. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15177. }
  15178. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15179. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15180. textures.push(texture);
  15181. attachments.push(attachment);
  15182. gl.activeTexture(gl["TEXTURE" + i]);
  15183. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15188. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15189. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15190. if (generateMipMaps) {
  15191. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15192. }
  15193. // Unbind
  15194. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15195. texture._framebuffer = framebuffer;
  15196. texture._depthStencilBuffer = depthStencilBuffer;
  15197. texture.baseWidth = width;
  15198. texture.baseHeight = height;
  15199. texture.width = width;
  15200. texture.height = height;
  15201. texture.isReady = true;
  15202. texture.samples = 1;
  15203. texture.generateMipMaps = generateMipMaps;
  15204. texture.samplingMode = samplingMode;
  15205. texture.type = type;
  15206. texture._generateDepthBuffer = generateDepthBuffer;
  15207. texture._generateStencilBuffer = generateStencilBuffer;
  15208. texture._attachments = attachments;
  15209. this._internalTexturesCache.push(texture);
  15210. }
  15211. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15212. // Depth texture
  15213. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15214. gl.activeTexture(gl.TEXTURE0);
  15215. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15220. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  15221. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15222. depthTexture._framebuffer = framebuffer;
  15223. depthTexture.baseWidth = width;
  15224. depthTexture.baseHeight = height;
  15225. depthTexture.width = width;
  15226. depthTexture.height = height;
  15227. depthTexture.isReady = true;
  15228. depthTexture.samples = 1;
  15229. depthTexture.generateMipMaps = generateMipMaps;
  15230. depthTexture.samplingMode = gl.NEAREST;
  15231. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15232. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15233. textures.push(depthTexture);
  15234. this._internalTexturesCache.push(depthTexture);
  15235. }
  15236. gl.drawBuffers(attachments);
  15237. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15238. this.bindUnboundFramebuffer(null);
  15239. this.resetTextureCache();
  15240. return textures;
  15241. };
  15242. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15243. if (samples === void 0) { samples = 1; }
  15244. var depthStencilBuffer = null;
  15245. var gl = this._gl;
  15246. // Create the depth/stencil buffer
  15247. if (generateStencilBuffer) {
  15248. depthStencilBuffer = gl.createRenderbuffer();
  15249. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15250. if (samples > 1) {
  15251. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15252. }
  15253. else {
  15254. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15255. }
  15256. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15257. }
  15258. else if (generateDepthBuffer) {
  15259. depthStencilBuffer = gl.createRenderbuffer();
  15260. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15261. if (samples > 1) {
  15262. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15263. }
  15264. else {
  15265. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15266. }
  15267. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15268. }
  15269. return depthStencilBuffer;
  15270. };
  15271. /**
  15272. * Updates the sample count of a render target texture
  15273. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15274. * @param texture defines the texture to update
  15275. * @param samples defines the sample count to set
  15276. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15277. */
  15278. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15279. if (this.webGLVersion < 2 || !texture) {
  15280. return 1;
  15281. }
  15282. if (texture.samples === samples) {
  15283. return samples;
  15284. }
  15285. var gl = this._gl;
  15286. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15287. // Dispose previous render buffers
  15288. if (texture._depthStencilBuffer) {
  15289. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15290. texture._depthStencilBuffer = null;
  15291. }
  15292. if (texture._MSAAFramebuffer) {
  15293. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15294. texture._MSAAFramebuffer = null;
  15295. }
  15296. if (texture._MSAARenderBuffer) {
  15297. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15298. texture._MSAARenderBuffer = null;
  15299. }
  15300. if (samples > 1) {
  15301. var framebuffer = gl.createFramebuffer();
  15302. if (!framebuffer) {
  15303. throw new Error("Unable to create multi sampled framebuffer");
  15304. }
  15305. texture._MSAAFramebuffer = framebuffer;
  15306. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15307. var colorRenderbuffer = gl.createRenderbuffer();
  15308. if (!colorRenderbuffer) {
  15309. throw new Error("Unable to create multi sampled framebuffer");
  15310. }
  15311. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15312. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15313. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15314. texture._MSAARenderBuffer = colorRenderbuffer;
  15315. }
  15316. else {
  15317. this.bindUnboundFramebuffer(texture._framebuffer);
  15318. }
  15319. texture.samples = samples;
  15320. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15321. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15322. this.bindUnboundFramebuffer(null);
  15323. return samples;
  15324. };
  15325. /**
  15326. * Update the sample count for a given multiple render target texture
  15327. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15328. * @param textures defines the textures to update
  15329. * @param samples defines the sample count to set
  15330. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15331. */
  15332. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15333. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15334. return 1;
  15335. }
  15336. if (textures[0].samples === samples) {
  15337. return samples;
  15338. }
  15339. var gl = this._gl;
  15340. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15341. // Dispose previous render buffers
  15342. if (textures[0]._depthStencilBuffer) {
  15343. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15344. textures[0]._depthStencilBuffer = null;
  15345. }
  15346. if (textures[0]._MSAAFramebuffer) {
  15347. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15348. textures[0]._MSAAFramebuffer = null;
  15349. }
  15350. for (var i = 0; i < textures.length; i++) {
  15351. if (textures[i]._MSAARenderBuffer) {
  15352. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15353. textures[i]._MSAARenderBuffer = null;
  15354. }
  15355. }
  15356. if (samples > 1) {
  15357. var framebuffer = gl.createFramebuffer();
  15358. if (!framebuffer) {
  15359. throw new Error("Unable to create multi sampled framebuffer");
  15360. }
  15361. this.bindUnboundFramebuffer(framebuffer);
  15362. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15363. var attachments = [];
  15364. for (var i = 0; i < textures.length; i++) {
  15365. var texture = textures[i];
  15366. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15367. var colorRenderbuffer = gl.createRenderbuffer();
  15368. if (!colorRenderbuffer) {
  15369. throw new Error("Unable to create multi sampled framebuffer");
  15370. }
  15371. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15372. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15373. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15374. texture._MSAAFramebuffer = framebuffer;
  15375. texture._MSAARenderBuffer = colorRenderbuffer;
  15376. texture.samples = samples;
  15377. texture._depthStencilBuffer = depthStencilBuffer;
  15378. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15379. attachments.push(attachment);
  15380. }
  15381. gl.drawBuffers(attachments);
  15382. }
  15383. else {
  15384. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15385. }
  15386. this.bindUnboundFramebuffer(null);
  15387. return samples;
  15388. };
  15389. /** @hidden */
  15390. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15391. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15392. };
  15393. /** @hidden */
  15394. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15395. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15396. };
  15397. /**
  15398. * Creates a new render target cube texture
  15399. * @param size defines the size of the texture
  15400. * @param options defines the options used to create the texture
  15401. * @returns a new render target cube texture stored in an InternalTexture
  15402. */
  15403. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15404. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15405. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15406. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15407. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15408. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15409. }
  15410. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15411. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15412. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15413. }
  15414. var gl = this._gl;
  15415. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15416. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15417. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15418. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15419. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15420. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15421. }
  15422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15426. for (var face = 0; face < 6; face++) {
  15427. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15428. }
  15429. // Create the framebuffer
  15430. var framebuffer = gl.createFramebuffer();
  15431. this.bindUnboundFramebuffer(framebuffer);
  15432. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15433. // MipMaps
  15434. if (fullOptions.generateMipMaps) {
  15435. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15436. }
  15437. // Unbind
  15438. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15439. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15440. this.bindUnboundFramebuffer(null);
  15441. texture._framebuffer = framebuffer;
  15442. texture.width = size;
  15443. texture.height = size;
  15444. texture.isReady = true;
  15445. texture.isCube = true;
  15446. texture.samples = 1;
  15447. texture.generateMipMaps = fullOptions.generateMipMaps;
  15448. texture.samplingMode = fullOptions.samplingMode;
  15449. texture.type = fullOptions.type;
  15450. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15451. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15452. this._internalTexturesCache.push(texture);
  15453. return texture;
  15454. };
  15455. /**
  15456. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15457. * @param rootUrl defines the url where the file to load is located
  15458. * @param scene defines the current scene
  15459. * @param scale defines scale to apply to the mip map selection
  15460. * @param offset defines offset to apply to the mip map selection
  15461. * @param onLoad defines an optional callback raised when the texture is loaded
  15462. * @param onError defines an optional callback raised if there is an issue to load the texture
  15463. * @param format defines the format of the data
  15464. * @param forcedExtension defines the extension to use to pick the right loader
  15465. * @returns the cube texture as an InternalTexture
  15466. */
  15467. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15468. var _this = this;
  15469. if (onLoad === void 0) { onLoad = null; }
  15470. if (onError === void 0) { onError = null; }
  15471. if (forcedExtension === void 0) { forcedExtension = null; }
  15472. var callback = function (loadData) {
  15473. if (!loadData) {
  15474. if (onLoad) {
  15475. onLoad(null);
  15476. }
  15477. return;
  15478. }
  15479. var texture = loadData.texture;
  15480. if (loadData.info.sphericalPolynomial) {
  15481. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15482. }
  15483. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15484. texture._lodGenerationScale = scale;
  15485. texture._lodGenerationOffset = offset;
  15486. if (_this._caps.textureLOD) {
  15487. // Do not add extra process if texture lod is supported.
  15488. if (onLoad) {
  15489. onLoad(texture);
  15490. }
  15491. return;
  15492. }
  15493. var mipSlices = 3;
  15494. var gl = _this._gl;
  15495. var width = loadData.width;
  15496. if (!width) {
  15497. return;
  15498. }
  15499. var textures = [];
  15500. for (var i = 0; i < mipSlices; i++) {
  15501. //compute LOD from even spacing in smoothness (matching shader calculation)
  15502. var smoothness = i / (mipSlices - 1);
  15503. var roughness = 1 - smoothness;
  15504. var minLODIndex = offset; // roughness = 0
  15505. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15506. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15507. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15508. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15509. glTextureFromLod.isCube = true;
  15510. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15512. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15515. if (loadData.isDDS) {
  15516. var info = loadData.info;
  15517. var data = loadData.data;
  15518. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15519. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15520. }
  15521. else {
  15522. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15523. }
  15524. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15525. // Wrap in a base texture for easy binding.
  15526. var lodTexture = new BABYLON.BaseTexture(scene);
  15527. lodTexture.isCube = true;
  15528. lodTexture._texture = glTextureFromLod;
  15529. glTextureFromLod.isReady = true;
  15530. textures.push(lodTexture);
  15531. }
  15532. texture._lodTextureHigh = textures[2];
  15533. texture._lodTextureMid = textures[1];
  15534. texture._lodTextureLow = textures[0];
  15535. if (onLoad) {
  15536. onLoad(texture);
  15537. }
  15538. };
  15539. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15540. };
  15541. /**
  15542. * Creates a cube texture
  15543. * @param rootUrl defines the url where the files to load is located
  15544. * @param scene defines the current scene
  15545. * @param files defines the list of files to load (1 per face)
  15546. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15547. * @param onLoad defines an optional callback raised when the texture is loaded
  15548. * @param onError defines an optional callback raised if there is an issue to load the texture
  15549. * @param format defines the format of the data
  15550. * @param forcedExtension defines the extension to use to pick the right loader
  15551. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15552. * @returns the cube texture as an InternalTexture
  15553. */
  15554. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15555. var _this = this;
  15556. if (onLoad === void 0) { onLoad = null; }
  15557. if (onError === void 0) { onError = null; }
  15558. if (forcedExtension === void 0) { forcedExtension = null; }
  15559. if (createPolynomials === void 0) { createPolynomials = false; }
  15560. var gl = this._gl;
  15561. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15562. texture.isCube = true;
  15563. texture.url = rootUrl;
  15564. texture.generateMipMaps = !noMipmap;
  15565. if (!this._doNotHandleContextLost) {
  15566. texture._extension = forcedExtension;
  15567. texture._files = files;
  15568. }
  15569. var isKTX = false;
  15570. var isDDS = false;
  15571. var lastDot = rootUrl.lastIndexOf('.');
  15572. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15573. if (this._textureFormatInUse) {
  15574. extension = this._textureFormatInUse;
  15575. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15576. isKTX = true;
  15577. }
  15578. else {
  15579. isDDS = (extension === ".dds");
  15580. }
  15581. var onerror = function (request, exception) {
  15582. if (onError && request) {
  15583. onError(request.status + " " + request.statusText, exception);
  15584. }
  15585. };
  15586. if (isKTX) {
  15587. this._loadFile(rootUrl, function (data) {
  15588. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15589. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15590. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15591. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15592. ktx.uploadLevels(_this._gl, !noMipmap);
  15593. _this.setCubeMapTextureParams(gl, loadMipmap);
  15594. texture.width = ktx.pixelWidth;
  15595. texture.height = ktx.pixelHeight;
  15596. texture.isReady = true;
  15597. }, undefined, undefined, true, onerror);
  15598. }
  15599. else if (isDDS) {
  15600. if (files && files.length === 6) {
  15601. this._cascadeLoadFiles(scene, function (imgs) {
  15602. var info;
  15603. var loadMipmap = false;
  15604. var width = 0;
  15605. for (var index = 0; index < imgs.length; index++) {
  15606. var data = imgs[index];
  15607. info = BABYLON.DDSTools.GetDDSInfo(data);
  15608. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15609. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15610. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15611. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15612. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15613. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15614. }
  15615. texture.width = info.width;
  15616. texture.height = info.height;
  15617. texture.type = info.textureType;
  15618. width = info.width;
  15619. }
  15620. _this.setCubeMapTextureParams(gl, loadMipmap);
  15621. texture.isReady = true;
  15622. if (onLoad) {
  15623. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15624. }
  15625. }, files, onError);
  15626. }
  15627. else {
  15628. this._loadFile(rootUrl, function (data) {
  15629. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15630. if (createPolynomials) {
  15631. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15632. }
  15633. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15634. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15635. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15636. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15637. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15638. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15639. }
  15640. _this.setCubeMapTextureParams(gl, loadMipmap);
  15641. texture.width = info.width;
  15642. texture.height = info.height;
  15643. texture.isReady = true;
  15644. texture.type = info.textureType;
  15645. if (onLoad) {
  15646. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15647. }
  15648. }, undefined, undefined, true, onerror);
  15649. }
  15650. }
  15651. else {
  15652. if (!files) {
  15653. throw new Error("Cannot load cubemap because files were not defined");
  15654. }
  15655. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15656. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15657. var height = width;
  15658. _this._prepareWorkingCanvas();
  15659. if (!_this._workingCanvas || !_this._workingContext) {
  15660. return;
  15661. }
  15662. _this._workingCanvas.width = width;
  15663. _this._workingCanvas.height = height;
  15664. var faces = [
  15665. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15666. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15667. ];
  15668. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15669. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15670. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15671. for (var index = 0; index < faces.length; index++) {
  15672. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15673. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15674. }
  15675. if (!noMipmap) {
  15676. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15677. }
  15678. _this.setCubeMapTextureParams(gl, !noMipmap);
  15679. texture.width = width;
  15680. texture.height = height;
  15681. texture.isReady = true;
  15682. if (format) {
  15683. texture.format = format;
  15684. }
  15685. texture.onLoadedObservable.notifyObservers(texture);
  15686. texture.onLoadedObservable.clear();
  15687. if (onLoad) {
  15688. onLoad();
  15689. }
  15690. }, files, onError);
  15691. }
  15692. this._internalTexturesCache.push(texture);
  15693. return texture;
  15694. };
  15695. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15700. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15701. // this.resetTextureCache();
  15702. };
  15703. /**
  15704. * Update a raw cube texture
  15705. * @param texture defines the texture to udpdate
  15706. * @param data defines the data to store
  15707. * @param format defines the data format
  15708. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15709. * @param invertY defines if data must be stored with Y axis inverted
  15710. * @param compression defines the compression used (null by default)
  15711. * @param level defines which level of the texture to update
  15712. */
  15713. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15714. if (compression === void 0) { compression = null; }
  15715. if (level === void 0) { level = 0; }
  15716. texture._bufferViewArray = data;
  15717. texture.format = format;
  15718. texture.type = type;
  15719. texture.invertY = invertY;
  15720. texture._compression = compression;
  15721. var gl = this._gl;
  15722. var textureType = this._getWebGLTextureType(type);
  15723. var internalFormat = this._getInternalFormat(format);
  15724. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15725. var needConversion = false;
  15726. if (internalFormat === gl.RGB) {
  15727. internalFormat = gl.RGBA;
  15728. needConversion = true;
  15729. }
  15730. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15731. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15732. if (texture.width % 4 !== 0) {
  15733. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15734. }
  15735. // Data are known to be in +X +Y +Z -X -Y -Z
  15736. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15737. var faceData = data[faceIndex];
  15738. if (compression) {
  15739. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15740. }
  15741. else {
  15742. if (needConversion) {
  15743. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15744. }
  15745. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15746. }
  15747. }
  15748. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15749. if (isPot && texture.generateMipMaps && level === 0) {
  15750. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15751. }
  15752. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15753. // this.resetTextureCache();
  15754. texture.isReady = true;
  15755. };
  15756. /**
  15757. * Creates a new raw cube texture
  15758. * @param data defines the array of data to use to create each face
  15759. * @param size defines the size of the textures
  15760. * @param format defines the format of the data
  15761. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15762. * @param generateMipMaps defines if the engine should generate the mip levels
  15763. * @param invertY defines if data must be stored with Y axis inverted
  15764. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15765. * @param compression defines the compression used (null by default)
  15766. * @returns the cube texture as an InternalTexture
  15767. */
  15768. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15769. if (compression === void 0) { compression = null; }
  15770. var gl = this._gl;
  15771. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15772. texture.isCube = true;
  15773. texture.generateMipMaps = generateMipMaps;
  15774. texture.format = format;
  15775. texture.type = type;
  15776. if (!this._doNotHandleContextLost) {
  15777. texture._bufferViewArray = data;
  15778. }
  15779. var textureType = this._getWebGLTextureType(type);
  15780. var internalFormat = this._getInternalFormat(format);
  15781. if (internalFormat === gl.RGB) {
  15782. internalFormat = gl.RGBA;
  15783. }
  15784. var width = size;
  15785. var height = width;
  15786. texture.width = width;
  15787. texture.height = height;
  15788. // Double check on POT to generate Mips.
  15789. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15790. if (!isPot) {
  15791. generateMipMaps = false;
  15792. }
  15793. // Upload data if needed. The texture won't be ready until then.
  15794. if (data) {
  15795. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15796. }
  15797. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15798. // Filters
  15799. if (data && generateMipMaps) {
  15800. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15801. }
  15802. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15805. }
  15806. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15809. }
  15810. else {
  15811. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15812. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15813. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15814. }
  15815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15817. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15818. return texture;
  15819. };
  15820. /**
  15821. * Creates a new raw cube texture from a specified url
  15822. * @param url defines the url where the data is located
  15823. * @param scene defines the current scene
  15824. * @param size defines the size of the textures
  15825. * @param format defines the format of the data
  15826. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15827. * @param noMipmap defines if the engine should avoid generating the mip levels
  15828. * @param callback defines a callback used to extract texture data from loaded data
  15829. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15830. * @param onLoad defines a callback called when texture is loaded
  15831. * @param onError defines a callback called if there is an error
  15832. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15833. * @param invertY defines if data must be stored with Y axis inverted
  15834. * @returns the cube texture as an InternalTexture
  15835. */
  15836. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15837. var _this = this;
  15838. if (onLoad === void 0) { onLoad = null; }
  15839. if (onError === void 0) { onError = null; }
  15840. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15841. if (invertY === void 0) { invertY = false; }
  15842. var gl = this._gl;
  15843. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15844. scene._addPendingData(texture);
  15845. texture.url = url;
  15846. this._internalTexturesCache.push(texture);
  15847. var onerror = function (request, exception) {
  15848. scene._removePendingData(texture);
  15849. if (onError && request) {
  15850. onError(request.status + " " + request.statusText, exception);
  15851. }
  15852. };
  15853. var internalCallback = function (data) {
  15854. var width = texture.width;
  15855. var faceDataArrays = callback(data);
  15856. if (!faceDataArrays) {
  15857. return;
  15858. }
  15859. if (mipmapGenerator) {
  15860. var textureType = _this._getWebGLTextureType(type);
  15861. var internalFormat = _this._getInternalFormat(format);
  15862. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15863. var needConversion = false;
  15864. if (internalFormat === gl.RGB) {
  15865. internalFormat = gl.RGBA;
  15866. needConversion = true;
  15867. }
  15868. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15869. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15870. var mipData = mipmapGenerator(faceDataArrays);
  15871. for (var level = 0; level < mipData.length; level++) {
  15872. var mipSize = width >> level;
  15873. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15874. var mipFaceData = mipData[level][faceIndex];
  15875. if (needConversion) {
  15876. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15877. }
  15878. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15879. }
  15880. }
  15881. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15882. }
  15883. else {
  15884. texture.generateMipMaps = !noMipmap;
  15885. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15886. }
  15887. texture.isReady = true;
  15888. // this.resetTextureCache();
  15889. scene._removePendingData(texture);
  15890. if (onLoad) {
  15891. onLoad();
  15892. }
  15893. };
  15894. this._loadFile(url, function (data) {
  15895. internalCallback(data);
  15896. }, undefined, scene.database, true, onerror);
  15897. return texture;
  15898. };
  15899. ;
  15900. /**
  15901. * Update a raw 3D texture
  15902. * @param texture defines the texture to update
  15903. * @param data defines the data to store
  15904. * @param format defines the data format
  15905. * @param invertY defines if data must be stored with Y axis inverted
  15906. * @param compression defines the used compression (can be null)
  15907. */
  15908. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15909. if (compression === void 0) { compression = null; }
  15910. var internalFormat = this._getInternalFormat(format);
  15911. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15912. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15913. if (!this._doNotHandleContextLost) {
  15914. texture._bufferView = data;
  15915. texture.format = format;
  15916. texture.invertY = invertY;
  15917. texture._compression = compression;
  15918. }
  15919. if (texture.width % 4 !== 0) {
  15920. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15921. }
  15922. if (compression && data) {
  15923. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15924. }
  15925. else {
  15926. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15927. }
  15928. if (texture.generateMipMaps) {
  15929. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15930. }
  15931. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15932. // this.resetTextureCache();
  15933. texture.isReady = true;
  15934. };
  15935. /**
  15936. * Creates a new raw 3D texture
  15937. * @param data defines the data used to create the texture
  15938. * @param width defines the width of the texture
  15939. * @param height defines the height of the texture
  15940. * @param depth defines the depth of the texture
  15941. * @param format defines the format of the texture
  15942. * @param generateMipMaps defines if the engine must generate mip levels
  15943. * @param invertY defines if data must be stored with Y axis inverted
  15944. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15945. * @param compression defines the compressed used (can be null)
  15946. * @returns a new raw 3D texture (stored in an InternalTexture)
  15947. */
  15948. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15949. if (compression === void 0) { compression = null; }
  15950. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15951. texture.baseWidth = width;
  15952. texture.baseHeight = height;
  15953. texture.baseDepth = depth;
  15954. texture.width = width;
  15955. texture.height = height;
  15956. texture.depth = depth;
  15957. texture.format = format;
  15958. texture.generateMipMaps = generateMipMaps;
  15959. texture.samplingMode = samplingMode;
  15960. texture.is3D = true;
  15961. if (!this._doNotHandleContextLost) {
  15962. texture._bufferView = data;
  15963. }
  15964. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15965. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15966. // Filters
  15967. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15968. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15969. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15970. if (generateMipMaps) {
  15971. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15972. }
  15973. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15974. this._internalTexturesCache.push(texture);
  15975. return texture;
  15976. };
  15977. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15978. var gl = this._gl;
  15979. if (!gl) {
  15980. return;
  15981. }
  15982. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15983. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15985. if (!noMipmap && !isCompressed) {
  15986. gl.generateMipmap(gl.TEXTURE_2D);
  15987. }
  15988. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15989. // this.resetTextureCache();
  15990. if (scene) {
  15991. scene._removePendingData(texture);
  15992. }
  15993. texture.onLoadedObservable.notifyObservers(texture);
  15994. texture.onLoadedObservable.clear();
  15995. };
  15996. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15997. var _this = this;
  15998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15999. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16000. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16001. var gl = this._gl;
  16002. if (!gl) {
  16003. return;
  16004. }
  16005. if (!texture._webGLTexture) {
  16006. // this.resetTextureCache();
  16007. if (scene) {
  16008. scene._removePendingData(texture);
  16009. }
  16010. return;
  16011. }
  16012. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16013. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16014. texture.baseWidth = width;
  16015. texture.baseHeight = height;
  16016. texture.width = potWidth;
  16017. texture.height = potHeight;
  16018. texture.isReady = true;
  16019. if (processFunction(potWidth, potHeight, function () {
  16020. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16021. })) {
  16022. // Returning as texture needs extra async steps
  16023. return;
  16024. }
  16025. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16026. };
  16027. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16028. // Create new RGBA data container.
  16029. var rgbaData;
  16030. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16031. rgbaData = new Float32Array(width * height * 4);
  16032. }
  16033. else {
  16034. rgbaData = new Uint32Array(width * height * 4);
  16035. }
  16036. // Convert each pixel.
  16037. for (var x = 0; x < width; x++) {
  16038. for (var y = 0; y < height; y++) {
  16039. var index = (y * width + x) * 3;
  16040. var newIndex = (y * width + x) * 4;
  16041. // Map Old Value to new value.
  16042. rgbaData[newIndex + 0] = rgbData[index + 0];
  16043. rgbaData[newIndex + 1] = rgbData[index + 1];
  16044. rgbaData[newIndex + 2] = rgbData[index + 2];
  16045. // Add fully opaque alpha channel.
  16046. rgbaData[newIndex + 3] = 1;
  16047. }
  16048. }
  16049. return rgbaData;
  16050. };
  16051. /** @hidden */
  16052. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16053. var gl = this._gl;
  16054. if (texture._framebuffer) {
  16055. gl.deleteFramebuffer(texture._framebuffer);
  16056. texture._framebuffer = null;
  16057. }
  16058. if (texture._depthStencilBuffer) {
  16059. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16060. texture._depthStencilBuffer = null;
  16061. }
  16062. if (texture._MSAAFramebuffer) {
  16063. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16064. texture._MSAAFramebuffer = null;
  16065. }
  16066. if (texture._MSAARenderBuffer) {
  16067. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16068. texture._MSAARenderBuffer = null;
  16069. }
  16070. };
  16071. /** @hidden */
  16072. Engine.prototype._releaseTexture = function (texture) {
  16073. var gl = this._gl;
  16074. this._releaseFramebufferObjects(texture);
  16075. gl.deleteTexture(texture._webGLTexture);
  16076. // Unbind channels
  16077. this.unbindAllTextures();
  16078. var index = this._internalTexturesCache.indexOf(texture);
  16079. if (index !== -1) {
  16080. this._internalTexturesCache.splice(index, 1);
  16081. }
  16082. // Integrated fixed lod samplers.
  16083. if (texture._lodTextureHigh) {
  16084. texture._lodTextureHigh.dispose();
  16085. }
  16086. if (texture._lodTextureMid) {
  16087. texture._lodTextureMid.dispose();
  16088. }
  16089. if (texture._lodTextureLow) {
  16090. texture._lodTextureLow.dispose();
  16091. }
  16092. // Set output texture of post process to null if the texture has been released/disposed
  16093. this.scenes.forEach(function (scene) {
  16094. scene.postProcesses.forEach(function (postProcess) {
  16095. if (postProcess._outputTexture == texture) {
  16096. postProcess._outputTexture = null;
  16097. }
  16098. });
  16099. scene.cameras.forEach(function (camera) {
  16100. camera._postProcesses.forEach(function (postProcess) {
  16101. if (postProcess) {
  16102. if (postProcess._outputTexture == texture) {
  16103. postProcess._outputTexture = null;
  16104. }
  16105. }
  16106. });
  16107. });
  16108. });
  16109. };
  16110. Engine.prototype.setProgram = function (program) {
  16111. if (this._currentProgram !== program) {
  16112. this._gl.useProgram(program);
  16113. this._currentProgram = program;
  16114. }
  16115. };
  16116. /**
  16117. * Binds an effect to the webGL context
  16118. * @param effect defines the effect to bind
  16119. */
  16120. Engine.prototype.bindSamplers = function (effect) {
  16121. this.setProgram(effect.getProgram());
  16122. var samplers = effect.getSamplers();
  16123. for (var index = 0; index < samplers.length; index++) {
  16124. var uniform = effect.getUniform(samplers[index]);
  16125. if (uniform) {
  16126. this._boundUniforms[index] = uniform;
  16127. }
  16128. }
  16129. this._currentEffect = null;
  16130. };
  16131. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16132. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16133. return;
  16134. }
  16135. // Remove
  16136. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16137. // Bind last to it
  16138. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16139. // Bind to dummy
  16140. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16141. };
  16142. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16143. if (!internalTexture) {
  16144. return -1;
  16145. }
  16146. internalTexture._initialSlot = channel;
  16147. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16148. if (channel !== internalTexture._designatedSlot) {
  16149. this._textureCollisions.addCount(1, false);
  16150. }
  16151. }
  16152. else {
  16153. if (channel !== internalTexture._designatedSlot) {
  16154. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16155. return internalTexture._designatedSlot;
  16156. }
  16157. else {
  16158. // No slot for this texture, let's pick a new one (if we find a free slot)
  16159. if (this._nextFreeTextureSlots.length) {
  16160. return this._nextFreeTextureSlots[0];
  16161. }
  16162. // We need to recycle the oldest bound texture, sorry.
  16163. this._textureCollisions.addCount(1, false);
  16164. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16165. }
  16166. }
  16167. }
  16168. return channel;
  16169. };
  16170. Engine.prototype._linkTrackers = function (previous, next) {
  16171. previous.next = next;
  16172. next.previous = previous;
  16173. };
  16174. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16175. var currentSlot = internalTexture._designatedSlot;
  16176. if (currentSlot === -1) {
  16177. return -1;
  16178. }
  16179. internalTexture._designatedSlot = -1;
  16180. if (this.disableTextureBindingOptimization) {
  16181. return -1;
  16182. }
  16183. // Remove from bound list
  16184. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16185. // Free the slot
  16186. this._boundTexturesCache[currentSlot] = null;
  16187. this._nextFreeTextureSlots.push(currentSlot);
  16188. return currentSlot;
  16189. };
  16190. Engine.prototype._activateCurrentTexture = function () {
  16191. if (this._currentTextureChannel !== this._activeChannel) {
  16192. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16193. this._currentTextureChannel = this._activeChannel;
  16194. }
  16195. };
  16196. /** @hidden */
  16197. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16198. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16199. if (force === void 0) { force = false; }
  16200. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16201. this._activeChannel = texture._designatedSlot;
  16202. }
  16203. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16204. var isTextureForRendering = texture && texture._initialSlot > -1;
  16205. if (currentTextureBound !== texture || force) {
  16206. if (currentTextureBound) {
  16207. this._removeDesignatedSlot(currentTextureBound);
  16208. }
  16209. this._activateCurrentTexture();
  16210. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16211. this._boundTexturesCache[this._activeChannel] = texture;
  16212. if (texture) {
  16213. if (!this.disableTextureBindingOptimization) {
  16214. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16215. if (slotIndex > -1) {
  16216. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16217. }
  16218. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16219. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16220. }
  16221. texture._designatedSlot = this._activeChannel;
  16222. }
  16223. }
  16224. else if (forTextureDataUpdate) {
  16225. this._activateCurrentTexture();
  16226. }
  16227. if (isTextureForRendering && !forTextureDataUpdate) {
  16228. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16229. }
  16230. };
  16231. /** @hidden */
  16232. Engine.prototype._bindTexture = function (channel, texture) {
  16233. if (channel < 0) {
  16234. return;
  16235. }
  16236. if (texture) {
  16237. channel = this._getCorrectTextureChannel(channel, texture);
  16238. }
  16239. this._activeChannel = channel;
  16240. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16241. };
  16242. /**
  16243. * Sets a texture to the webGL context from a postprocess
  16244. * @param channel defines the channel to use
  16245. * @param postProcess defines the source postprocess
  16246. */
  16247. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16248. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16249. };
  16250. /**
  16251. * Binds the output of the passed in post process to the texture channel specified
  16252. * @param channel The channel the texture should be bound to
  16253. * @param postProcess The post process which's output should be bound
  16254. */
  16255. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16256. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16257. };
  16258. /**
  16259. * Unbind all textures from the webGL context
  16260. */
  16261. Engine.prototype.unbindAllTextures = function () {
  16262. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16263. this._activeChannel = channel;
  16264. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16265. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16266. if (this.webGLVersion > 1) {
  16267. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16268. }
  16269. }
  16270. };
  16271. /**
  16272. * Sets a texture to the according uniform.
  16273. * @param channel The texture channel
  16274. * @param uniform The uniform to set
  16275. * @param texture The texture to apply
  16276. */
  16277. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16278. if (channel < 0) {
  16279. return;
  16280. }
  16281. if (uniform) {
  16282. this._boundUniforms[channel] = uniform;
  16283. }
  16284. this._setTexture(channel, texture);
  16285. };
  16286. /**
  16287. * Sets a depth stencil texture from a render target to the according uniform.
  16288. * @param channel The texture channel
  16289. * @param uniform The uniform to set
  16290. * @param texture The render target texture containing the depth stencil texture to apply
  16291. */
  16292. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16293. if (channel < 0) {
  16294. return;
  16295. }
  16296. if (uniform) {
  16297. this._boundUniforms[channel] = uniform;
  16298. }
  16299. if (!texture || !texture.depthStencilTexture) {
  16300. this._setTexture(channel, null);
  16301. }
  16302. else {
  16303. this._setTexture(channel, texture, false, true);
  16304. }
  16305. };
  16306. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16307. var uniform = this._boundUniforms[sourceSlot];
  16308. if (uniform._currentState === destination) {
  16309. return;
  16310. }
  16311. this._gl.uniform1i(uniform, destination);
  16312. uniform._currentState = destination;
  16313. };
  16314. Engine.prototype._getTextureWrapMode = function (mode) {
  16315. switch (mode) {
  16316. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16317. return this._gl.REPEAT;
  16318. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16319. return this._gl.CLAMP_TO_EDGE;
  16320. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16321. return this._gl.MIRRORED_REPEAT;
  16322. }
  16323. return this._gl.REPEAT;
  16324. };
  16325. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16326. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16327. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16328. // Not ready?
  16329. if (!texture) {
  16330. if (this._boundTexturesCache[channel] != null) {
  16331. this._activeChannel = channel;
  16332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16333. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16334. if (this.webGLVersion > 1) {
  16335. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16336. }
  16337. }
  16338. return false;
  16339. }
  16340. // Video
  16341. if (texture.video) {
  16342. this._activeChannel = channel;
  16343. texture.update();
  16344. }
  16345. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16346. texture.delayLoad();
  16347. return false;
  16348. }
  16349. var internalTexture;
  16350. if (depthStencilTexture) {
  16351. internalTexture = texture.depthStencilTexture;
  16352. }
  16353. else if (texture.isReady()) {
  16354. internalTexture = texture.getInternalTexture();
  16355. }
  16356. else if (texture.isCube) {
  16357. internalTexture = this.emptyCubeTexture;
  16358. }
  16359. else if (texture.is3D) {
  16360. internalTexture = this.emptyTexture3D;
  16361. }
  16362. else {
  16363. internalTexture = this.emptyTexture;
  16364. }
  16365. if (!isPartOfTextureArray) {
  16366. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16367. }
  16368. var needToBind = true;
  16369. if (this._boundTexturesCache[channel] === internalTexture) {
  16370. this._moveBoundTextureOnTop(internalTexture);
  16371. if (!isPartOfTextureArray) {
  16372. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16373. }
  16374. needToBind = false;
  16375. }
  16376. this._activeChannel = channel;
  16377. if (internalTexture && internalTexture.is3D) {
  16378. if (needToBind) {
  16379. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16380. }
  16381. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16382. internalTexture._cachedWrapU = texture.wrapU;
  16383. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16384. }
  16385. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16386. internalTexture._cachedWrapV = texture.wrapV;
  16387. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16388. }
  16389. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16390. internalTexture._cachedWrapR = texture.wrapR;
  16391. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16392. }
  16393. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16394. }
  16395. else if (internalTexture && internalTexture.isCube) {
  16396. if (needToBind) {
  16397. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16398. }
  16399. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16400. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16401. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16402. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16403. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16404. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16405. }
  16406. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16407. }
  16408. else {
  16409. if (needToBind) {
  16410. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16411. }
  16412. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16413. internalTexture._cachedWrapU = texture.wrapU;
  16414. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16415. }
  16416. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16417. internalTexture._cachedWrapV = texture.wrapV;
  16418. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16419. }
  16420. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16421. }
  16422. return true;
  16423. };
  16424. /**
  16425. * Sets an array of texture to the webGL context
  16426. * @param channel defines the channel where the texture array must be set
  16427. * @param uniform defines the associated uniform location
  16428. * @param textures defines the array of textures to bind
  16429. */
  16430. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16431. if (channel < 0 || !uniform) {
  16432. return;
  16433. }
  16434. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16435. this._textureUnits = new Int32Array(textures.length);
  16436. }
  16437. for (var i = 0; i < textures.length; i++) {
  16438. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16439. }
  16440. this._gl.uniform1iv(uniform, this._textureUnits);
  16441. for (var index = 0; index < textures.length; index++) {
  16442. this._setTexture(this._textureUnits[index], textures[index], true);
  16443. }
  16444. };
  16445. /** @hidden */
  16446. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16447. var internalTexture = texture.getInternalTexture();
  16448. if (!internalTexture) {
  16449. return;
  16450. }
  16451. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16452. var value = texture.anisotropicFilteringLevel;
  16453. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16454. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16455. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16456. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16457. }
  16458. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16459. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16460. internalTexture._cachedAnisotropicFilteringLevel = value;
  16461. }
  16462. };
  16463. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16464. this._bindTextureDirectly(target, texture, true, true);
  16465. this._gl.texParameterf(target, parameter, value);
  16466. };
  16467. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16468. if (texture) {
  16469. this._bindTextureDirectly(target, texture, true, true);
  16470. }
  16471. this._gl.texParameteri(target, parameter, value);
  16472. };
  16473. /**
  16474. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16475. * @param x defines the x coordinate of the rectangle where pixels must be read
  16476. * @param y defines the y coordinate of the rectangle where pixels must be read
  16477. * @param width defines the width of the rectangle where pixels must be read
  16478. * @param height defines the height of the rectangle where pixels must be read
  16479. * @returns a Uint8Array containing RGBA colors
  16480. */
  16481. Engine.prototype.readPixels = function (x, y, width, height) {
  16482. var data = new Uint8Array(height * width * 4);
  16483. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16484. return data;
  16485. };
  16486. /**
  16487. * Add an externaly attached data from its key.
  16488. * This method call will fail and return false, if such key already exists.
  16489. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16490. * @param key the unique key that identifies the data
  16491. * @param data the data object to associate to the key for this Engine instance
  16492. * @return true if no such key were already present and the data was added successfully, false otherwise
  16493. */
  16494. Engine.prototype.addExternalData = function (key, data) {
  16495. if (!this._externalData) {
  16496. this._externalData = new BABYLON.StringDictionary();
  16497. }
  16498. return this._externalData.add(key, data);
  16499. };
  16500. /**
  16501. * Get an externaly attached data from its key
  16502. * @param key the unique key that identifies the data
  16503. * @return the associated data, if present (can be null), or undefined if not present
  16504. */
  16505. Engine.prototype.getExternalData = function (key) {
  16506. if (!this._externalData) {
  16507. this._externalData = new BABYLON.StringDictionary();
  16508. }
  16509. return this._externalData.get(key);
  16510. };
  16511. /**
  16512. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16513. * @param key the unique key that identifies the data
  16514. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16515. * @return the associated data, can be null if the factory returned null.
  16516. */
  16517. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16518. if (!this._externalData) {
  16519. this._externalData = new BABYLON.StringDictionary();
  16520. }
  16521. return this._externalData.getOrAddWithFactory(key, factory);
  16522. };
  16523. /**
  16524. * Remove an externaly attached data from the Engine instance
  16525. * @param key the unique key that identifies the data
  16526. * @return true if the data was successfully removed, false if it doesn't exist
  16527. */
  16528. Engine.prototype.removeExternalData = function (key) {
  16529. if (!this._externalData) {
  16530. this._externalData = new BABYLON.StringDictionary();
  16531. }
  16532. return this._externalData.remove(key);
  16533. };
  16534. /**
  16535. * Unbind all vertex attributes from the webGL context
  16536. */
  16537. Engine.prototype.unbindAllAttributes = function () {
  16538. if (this._mustWipeVertexAttributes) {
  16539. this._mustWipeVertexAttributes = false;
  16540. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16541. this._gl.disableVertexAttribArray(i);
  16542. this._vertexAttribArraysEnabled[i] = false;
  16543. this._currentBufferPointers[i].active = false;
  16544. }
  16545. return;
  16546. }
  16547. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16548. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16549. continue;
  16550. }
  16551. this._gl.disableVertexAttribArray(i);
  16552. this._vertexAttribArraysEnabled[i] = false;
  16553. this._currentBufferPointers[i].active = false;
  16554. }
  16555. };
  16556. /**
  16557. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16558. */
  16559. Engine.prototype.releaseEffects = function () {
  16560. for (var name in this._compiledEffects) {
  16561. this._deleteProgram(this._compiledEffects[name]._program);
  16562. }
  16563. this._compiledEffects = {};
  16564. };
  16565. /**
  16566. * Dispose and release all associated resources
  16567. */
  16568. Engine.prototype.dispose = function () {
  16569. this.hideLoadingUI();
  16570. this.stopRenderLoop();
  16571. // Release postProcesses
  16572. while (this.postProcesses.length) {
  16573. this.postProcesses[0].dispose();
  16574. }
  16575. // Empty texture
  16576. if (this._emptyTexture) {
  16577. this._releaseTexture(this._emptyTexture);
  16578. this._emptyTexture = null;
  16579. }
  16580. if (this._emptyCubeTexture) {
  16581. this._releaseTexture(this._emptyCubeTexture);
  16582. this._emptyCubeTexture = null;
  16583. }
  16584. // Rescale PP
  16585. if (this._rescalePostProcess) {
  16586. this._rescalePostProcess.dispose();
  16587. }
  16588. // Release scenes
  16589. while (this.scenes.length) {
  16590. this.scenes[0].dispose();
  16591. }
  16592. // Release audio engine
  16593. if (Engine.audioEngine) {
  16594. Engine.audioEngine.dispose();
  16595. }
  16596. // Release effects
  16597. this.releaseEffects();
  16598. // Unbind
  16599. this.unbindAllAttributes();
  16600. this._boundUniforms = [];
  16601. if (this._dummyFramebuffer) {
  16602. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16603. }
  16604. //WebVR
  16605. this.disableVR();
  16606. // Events
  16607. if (BABYLON.Tools.IsWindowObjectExist()) {
  16608. window.removeEventListener("blur", this._onBlur);
  16609. window.removeEventListener("focus", this._onFocus);
  16610. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16611. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16612. if (this._renderingCanvas) {
  16613. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16614. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16615. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16616. if (!this._doNotHandleContextLost) {
  16617. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16618. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16619. }
  16620. }
  16621. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16622. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16623. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16624. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16625. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16626. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16627. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16628. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16629. if (this._onVrDisplayConnect) {
  16630. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16631. if (this._onVrDisplayDisconnect) {
  16632. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16633. }
  16634. if (this._onVrDisplayPresentChange) {
  16635. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16636. }
  16637. this._onVrDisplayConnect = null;
  16638. this._onVrDisplayDisconnect = null;
  16639. }
  16640. }
  16641. // Remove from Instances
  16642. var index = Engine.Instances.indexOf(this);
  16643. if (index >= 0) {
  16644. Engine.Instances.splice(index, 1);
  16645. }
  16646. this._workingCanvas = null;
  16647. this._workingContext = null;
  16648. this._currentBufferPointers = [];
  16649. this._renderingCanvas = null;
  16650. this._currentProgram = null;
  16651. this._bindedRenderFunction = null;
  16652. this.onResizeObservable.clear();
  16653. this.onCanvasBlurObservable.clear();
  16654. this.onCanvasFocusObservable.clear();
  16655. this.onCanvasPointerOutObservable.clear();
  16656. this.onBeginFrameObservable.clear();
  16657. this.onEndFrameObservable.clear();
  16658. BABYLON.Effect.ResetCache();
  16659. // Abort active requests
  16660. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16661. var request = _a[_i];
  16662. request.abort();
  16663. }
  16664. };
  16665. // Loading screen
  16666. /**
  16667. * Display the loading screen
  16668. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16669. */
  16670. Engine.prototype.displayLoadingUI = function () {
  16671. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16672. return;
  16673. }
  16674. var loadingScreen = this.loadingScreen;
  16675. if (loadingScreen) {
  16676. loadingScreen.displayLoadingUI();
  16677. }
  16678. };
  16679. /**
  16680. * Hide the loading screen
  16681. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16682. */
  16683. Engine.prototype.hideLoadingUI = function () {
  16684. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16685. return;
  16686. }
  16687. var loadingScreen = this.loadingScreen;
  16688. if (loadingScreen) {
  16689. loadingScreen.hideLoadingUI();
  16690. }
  16691. };
  16692. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16693. /**
  16694. * Gets the current loading screen object
  16695. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16696. */
  16697. get: function () {
  16698. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16699. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16700. return this._loadingScreen;
  16701. },
  16702. /**
  16703. * Sets the current loading screen object
  16704. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16705. */
  16706. set: function (loadingScreen) {
  16707. this._loadingScreen = loadingScreen;
  16708. },
  16709. enumerable: true,
  16710. configurable: true
  16711. });
  16712. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16713. /**
  16714. * Sets the current loading screen text
  16715. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16716. */
  16717. set: function (text) {
  16718. this.loadingScreen.loadingUIText = text;
  16719. },
  16720. enumerable: true,
  16721. configurable: true
  16722. });
  16723. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16724. /**
  16725. * Sets the current loading screen background color
  16726. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16727. */
  16728. set: function (color) {
  16729. this.loadingScreen.loadingUIBackgroundColor = color;
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. /**
  16735. * Attach a new callback raised when context lost event is fired
  16736. * @param callback defines the callback to call
  16737. */
  16738. Engine.prototype.attachContextLostEvent = function (callback) {
  16739. if (this._renderingCanvas) {
  16740. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16741. }
  16742. };
  16743. /**
  16744. * Attach a new callback raised when context restored event is fired
  16745. * @param callback defines the callback to call
  16746. */
  16747. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16748. if (this._renderingCanvas) {
  16749. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16750. }
  16751. };
  16752. /**
  16753. * Gets the source code of the vertex shader associated with a specific webGL program
  16754. * @param program defines the program to use
  16755. * @returns a string containing the source code of the vertex shader associated with the program
  16756. */
  16757. Engine.prototype.getVertexShaderSource = function (program) {
  16758. var shaders = this._gl.getAttachedShaders(program);
  16759. if (!shaders) {
  16760. return null;
  16761. }
  16762. return this._gl.getShaderSource(shaders[0]);
  16763. };
  16764. /**
  16765. * Gets the source code of the fragment shader associated with a specific webGL program
  16766. * @param program defines the program to use
  16767. * @returns a string containing the source code of the fragment shader associated with the program
  16768. */
  16769. Engine.prototype.getFragmentShaderSource = function (program) {
  16770. var shaders = this._gl.getAttachedShaders(program);
  16771. if (!shaders) {
  16772. return null;
  16773. }
  16774. return this._gl.getShaderSource(shaders[1]);
  16775. };
  16776. /**
  16777. * Get the current error code of the webGL context
  16778. * @returns the error code
  16779. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16780. */
  16781. Engine.prototype.getError = function () {
  16782. return this._gl.getError();
  16783. };
  16784. // FPS
  16785. /**
  16786. * Gets the current framerate
  16787. * @returns a number representing the framerate
  16788. */
  16789. Engine.prototype.getFps = function () {
  16790. return this._fps;
  16791. };
  16792. /**
  16793. * Gets the time spent between current and previous frame
  16794. * @returns a number representing the delta time in ms
  16795. */
  16796. Engine.prototype.getDeltaTime = function () {
  16797. return this._deltaTime;
  16798. };
  16799. Engine.prototype._measureFps = function () {
  16800. this._performanceMonitor.sampleFrame();
  16801. this._fps = this._performanceMonitor.averageFPS;
  16802. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16803. };
  16804. /** @hidden */
  16805. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16806. if (faceIndex === void 0) { faceIndex = -1; }
  16807. var gl = this._gl;
  16808. if (!this._dummyFramebuffer) {
  16809. var dummy = gl.createFramebuffer();
  16810. if (!dummy) {
  16811. throw new Error("Unable to create dummy framebuffer");
  16812. }
  16813. this._dummyFramebuffer = dummy;
  16814. }
  16815. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16816. if (faceIndex > -1) {
  16817. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16818. }
  16819. else {
  16820. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16821. }
  16822. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16823. var buffer;
  16824. switch (readType) {
  16825. case gl.UNSIGNED_BYTE:
  16826. buffer = new Uint8Array(4 * width * height);
  16827. readType = gl.UNSIGNED_BYTE;
  16828. break;
  16829. default:
  16830. buffer = new Float32Array(4 * width * height);
  16831. readType = gl.FLOAT;
  16832. break;
  16833. }
  16834. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16835. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16836. return buffer;
  16837. };
  16838. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16839. if (this._webGLVersion > 1) {
  16840. return this._caps.colorBufferFloat;
  16841. }
  16842. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16843. };
  16844. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16845. if (this._webGLVersion > 1) {
  16846. return this._caps.colorBufferFloat;
  16847. }
  16848. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16849. };
  16850. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16851. Engine.prototype._canRenderToFramebuffer = function (type) {
  16852. var gl = this._gl;
  16853. //clear existing errors
  16854. while (gl.getError() !== gl.NO_ERROR) { }
  16855. var successful = true;
  16856. var texture = gl.createTexture();
  16857. gl.bindTexture(gl.TEXTURE_2D, texture);
  16858. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16859. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16860. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16861. var fb = gl.createFramebuffer();
  16862. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16863. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16864. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16865. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16866. successful = successful && (gl.getError() === gl.NO_ERROR);
  16867. //try render by clearing frame buffer's color buffer
  16868. if (successful) {
  16869. gl.clear(gl.COLOR_BUFFER_BIT);
  16870. successful = successful && (gl.getError() === gl.NO_ERROR);
  16871. }
  16872. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16873. if (successful) {
  16874. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16875. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16876. var readFormat = gl.RGBA;
  16877. var readType = gl.UNSIGNED_BYTE;
  16878. var buffer = new Uint8Array(4);
  16879. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16880. successful = successful && (gl.getError() === gl.NO_ERROR);
  16881. }
  16882. //clean up
  16883. gl.deleteTexture(texture);
  16884. gl.deleteFramebuffer(fb);
  16885. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16886. //clear accumulated errors
  16887. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16888. return successful;
  16889. };
  16890. /** @hidden */
  16891. Engine.prototype._getWebGLTextureType = function (type) {
  16892. if (type === Engine.TEXTURETYPE_FLOAT) {
  16893. return this._gl.FLOAT;
  16894. }
  16895. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16896. // Add Half Float Constant.
  16897. return this._gl.HALF_FLOAT_OES;
  16898. }
  16899. return this._gl.UNSIGNED_BYTE;
  16900. };
  16901. ;
  16902. Engine.prototype._getInternalFormat = function (format) {
  16903. var internalFormat = this._gl.RGBA;
  16904. switch (format) {
  16905. case Engine.TEXTUREFORMAT_ALPHA:
  16906. internalFormat = this._gl.ALPHA;
  16907. break;
  16908. case Engine.TEXTUREFORMAT_LUMINANCE:
  16909. internalFormat = this._gl.LUMINANCE;
  16910. break;
  16911. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16912. internalFormat = this._gl.LUMINANCE_ALPHA;
  16913. break;
  16914. case Engine.TEXTUREFORMAT_RGB:
  16915. case Engine.TEXTUREFORMAT_RGB32F:
  16916. internalFormat = this._gl.RGB;
  16917. break;
  16918. case Engine.TEXTUREFORMAT_RGBA:
  16919. case Engine.TEXTUREFORMAT_RGBA32F:
  16920. internalFormat = this._gl.RGBA;
  16921. break;
  16922. case Engine.TEXTUREFORMAT_R32F:
  16923. internalFormat = this._gl.RED;
  16924. break;
  16925. case Engine.TEXTUREFORMAT_RG32F:
  16926. internalFormat = this._gl.RG;
  16927. break;
  16928. }
  16929. return internalFormat;
  16930. };
  16931. /** @hidden */
  16932. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16933. if (this._webGLVersion === 1) {
  16934. if (format) {
  16935. switch (format) {
  16936. case Engine.TEXTUREFORMAT_LUMINANCE:
  16937. return this._gl.LUMINANCE;
  16938. }
  16939. }
  16940. return this._gl.RGBA;
  16941. }
  16942. if (type === Engine.TEXTURETYPE_FLOAT) {
  16943. if (format) {
  16944. switch (format) {
  16945. case Engine.TEXTUREFORMAT_R32F:
  16946. return this._gl.R32F;
  16947. case Engine.TEXTUREFORMAT_RG32F:
  16948. return this._gl.RG32F;
  16949. case Engine.TEXTUREFORMAT_RGB32F:
  16950. return this._gl.RGB32F;
  16951. }
  16952. }
  16953. return this._gl.RGBA32F;
  16954. }
  16955. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16956. return this._gl.RGBA16F;
  16957. }
  16958. if (format) {
  16959. switch (format) {
  16960. case Engine.TEXTUREFORMAT_LUMINANCE:
  16961. return this._gl.LUMINANCE;
  16962. case Engine.TEXTUREFORMAT_RGB:
  16963. return this._gl.RGB;
  16964. }
  16965. }
  16966. return this._gl.RGBA;
  16967. };
  16968. ;
  16969. /** @hidden */
  16970. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16971. if (type === Engine.TEXTURETYPE_FLOAT) {
  16972. return this._gl.RGBA32F;
  16973. }
  16974. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16975. return this._gl.RGBA16F;
  16976. }
  16977. return this._gl.RGBA8;
  16978. };
  16979. ;
  16980. /**
  16981. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16982. * @return the new query
  16983. */
  16984. Engine.prototype.createQuery = function () {
  16985. return this._gl.createQuery();
  16986. };
  16987. /**
  16988. * Delete and release a webGL query
  16989. * @param query defines the query to delete
  16990. * @return the current engine
  16991. */
  16992. Engine.prototype.deleteQuery = function (query) {
  16993. this._gl.deleteQuery(query);
  16994. return this;
  16995. };
  16996. /**
  16997. * Check if a given query has resolved and got its value
  16998. * @param query defines the query to check
  16999. * @returns true if the query got its value
  17000. */
  17001. Engine.prototype.isQueryResultAvailable = function (query) {
  17002. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17003. };
  17004. /**
  17005. * Gets the value of a given query
  17006. * @param query defines the query to check
  17007. * @returns the value of the query
  17008. */
  17009. Engine.prototype.getQueryResult = function (query) {
  17010. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17011. };
  17012. /**
  17013. * Initiates an occlusion query
  17014. * @param algorithmType defines the algorithm to use
  17015. * @param query defines the query to use
  17016. * @returns the current engine
  17017. * @see http://doc.babylonjs.com/features/occlusionquery
  17018. */
  17019. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17020. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17021. this._gl.beginQuery(glAlgorithm, query);
  17022. return this;
  17023. };
  17024. /**
  17025. * Ends an occlusion query
  17026. * @see http://doc.babylonjs.com/features/occlusionquery
  17027. * @param algorithmType defines the algorithm to use
  17028. * @returns the current engine
  17029. */
  17030. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17031. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17032. this._gl.endQuery(glAlgorithm);
  17033. return this;
  17034. };
  17035. /* Time queries */
  17036. Engine.prototype._createTimeQuery = function () {
  17037. var timerQuery = this._caps.timerQuery;
  17038. if (timerQuery.createQueryEXT) {
  17039. return timerQuery.createQueryEXT();
  17040. }
  17041. return this.createQuery();
  17042. };
  17043. Engine.prototype._deleteTimeQuery = function (query) {
  17044. var timerQuery = this._caps.timerQuery;
  17045. if (timerQuery.deleteQueryEXT) {
  17046. timerQuery.deleteQueryEXT(query);
  17047. return;
  17048. }
  17049. this.deleteQuery(query);
  17050. };
  17051. Engine.prototype._getTimeQueryResult = function (query) {
  17052. var timerQuery = this._caps.timerQuery;
  17053. if (timerQuery.getQueryObjectEXT) {
  17054. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17055. }
  17056. return this.getQueryResult(query);
  17057. };
  17058. Engine.prototype._getTimeQueryAvailability = function (query) {
  17059. var timerQuery = this._caps.timerQuery;
  17060. if (timerQuery.getQueryObjectEXT) {
  17061. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17062. }
  17063. return this.isQueryResultAvailable(query);
  17064. };
  17065. /**
  17066. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17067. * Please note that only one query can be issued at a time
  17068. * @returns a time token used to track the time span
  17069. */
  17070. Engine.prototype.startTimeQuery = function () {
  17071. var timerQuery = this._caps.timerQuery;
  17072. if (!timerQuery) {
  17073. return null;
  17074. }
  17075. var token = new BABYLON._TimeToken();
  17076. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17077. if (this._caps.canUseTimestampForTimerQuery) {
  17078. token._startTimeQuery = this._createTimeQuery();
  17079. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17080. }
  17081. else {
  17082. if (this._currentNonTimestampToken) {
  17083. return this._currentNonTimestampToken;
  17084. }
  17085. token._timeElapsedQuery = this._createTimeQuery();
  17086. if (timerQuery.beginQueryEXT) {
  17087. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17088. }
  17089. else {
  17090. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17091. }
  17092. this._currentNonTimestampToken = token;
  17093. }
  17094. return token;
  17095. };
  17096. /**
  17097. * Ends a time query
  17098. * @param token defines the token used to measure the time span
  17099. * @returns the time spent (in ns)
  17100. */
  17101. Engine.prototype.endTimeQuery = function (token) {
  17102. var timerQuery = this._caps.timerQuery;
  17103. if (!timerQuery || !token) {
  17104. return -1;
  17105. }
  17106. if (this._caps.canUseTimestampForTimerQuery) {
  17107. if (!token._startTimeQuery) {
  17108. return -1;
  17109. }
  17110. if (!token._endTimeQuery) {
  17111. token._endTimeQuery = this._createTimeQuery();
  17112. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17113. }
  17114. }
  17115. else if (!token._timeElapsedQueryEnded) {
  17116. if (!token._timeElapsedQuery) {
  17117. return -1;
  17118. }
  17119. if (timerQuery.endQueryEXT) {
  17120. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17121. }
  17122. else {
  17123. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17124. }
  17125. token._timeElapsedQueryEnded = true;
  17126. }
  17127. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17128. var available = false;
  17129. if (token._endTimeQuery) {
  17130. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17131. }
  17132. else if (token._timeElapsedQuery) {
  17133. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17134. }
  17135. if (available && !disjoint) {
  17136. var result = 0;
  17137. if (this._caps.canUseTimestampForTimerQuery) {
  17138. if (!token._startTimeQuery || !token._endTimeQuery) {
  17139. return -1;
  17140. }
  17141. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17142. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17143. result = timeEnd - timeStart;
  17144. this._deleteTimeQuery(token._startTimeQuery);
  17145. this._deleteTimeQuery(token._endTimeQuery);
  17146. token._startTimeQuery = null;
  17147. token._endTimeQuery = null;
  17148. }
  17149. else {
  17150. if (!token._timeElapsedQuery) {
  17151. return -1;
  17152. }
  17153. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17154. this._deleteTimeQuery(token._timeElapsedQuery);
  17155. token._timeElapsedQuery = null;
  17156. token._timeElapsedQueryEnded = false;
  17157. this._currentNonTimestampToken = null;
  17158. }
  17159. return result;
  17160. }
  17161. return -1;
  17162. };
  17163. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17164. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17165. };
  17166. // Transform feedback
  17167. /**
  17168. * Creates a webGL transform feedback object
  17169. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17170. * @returns the webGL transform feedback object
  17171. */
  17172. Engine.prototype.createTransformFeedback = function () {
  17173. return this._gl.createTransformFeedback();
  17174. };
  17175. /**
  17176. * Delete a webGL transform feedback object
  17177. * @param value defines the webGL transform feedback object to delete
  17178. */
  17179. Engine.prototype.deleteTransformFeedback = function (value) {
  17180. this._gl.deleteTransformFeedback(value);
  17181. };
  17182. /**
  17183. * Bind a webGL transform feedback object to the webgl context
  17184. * @param value defines the webGL transform feedback object to bind
  17185. */
  17186. Engine.prototype.bindTransformFeedback = function (value) {
  17187. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17188. };
  17189. /**
  17190. * Begins a transform feedback operation
  17191. * @param usePoints defines if points or triangles must be used
  17192. */
  17193. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17194. if (usePoints === void 0) { usePoints = true; }
  17195. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17196. };
  17197. /**
  17198. * Ends a transform feedback operation
  17199. */
  17200. Engine.prototype.endTransformFeedback = function () {
  17201. this._gl.endTransformFeedback();
  17202. };
  17203. /**
  17204. * Specify the varyings to use with transform feedback
  17205. * @param program defines the associated webGL program
  17206. * @param value defines the list of strings representing the varying names
  17207. */
  17208. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17209. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17210. };
  17211. /**
  17212. * Bind a webGL buffer for a transform feedback operation
  17213. * @param value defines the webGL buffer to bind
  17214. */
  17215. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17216. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17217. };
  17218. /** @hidden */
  17219. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17220. var _this = this;
  17221. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17222. this._activeRequests.push(request);
  17223. request.onCompleteObservable.add(function (request) {
  17224. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17225. });
  17226. return request;
  17227. };
  17228. /** @hidden */
  17229. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17230. var _this = this;
  17231. return new Promise(function (resolve, reject) {
  17232. _this._loadFile(url, function (data) {
  17233. resolve(data);
  17234. }, undefined, database, useArrayBuffer, function (request, exception) {
  17235. reject(exception);
  17236. });
  17237. });
  17238. };
  17239. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17240. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17241. var onload = function (data) {
  17242. loadedFiles[index] = data;
  17243. loadedFiles._internalCount++;
  17244. if (loadedFiles._internalCount === 6) {
  17245. onfinish(loadedFiles);
  17246. }
  17247. };
  17248. var onerror = function (request, exception) {
  17249. if (onErrorCallBack && request) {
  17250. onErrorCallBack(request.status + " " + request.statusText, exception);
  17251. }
  17252. };
  17253. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17254. };
  17255. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17256. if (onError === void 0) { onError = null; }
  17257. var loadedFiles = [];
  17258. loadedFiles._internalCount = 0;
  17259. for (var index = 0; index < 6; index++) {
  17260. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17261. }
  17262. };
  17263. // Statics
  17264. /**
  17265. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17266. * @returns true if the engine can be created
  17267. * @ignorenaming
  17268. */
  17269. Engine.isSupported = function () {
  17270. try {
  17271. var tempcanvas = document.createElement("canvas");
  17272. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17273. return gl != null && !!window.WebGLRenderingContext;
  17274. }
  17275. catch (e) {
  17276. return false;
  17277. }
  17278. };
  17279. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17280. Engine.ExceptionList = [
  17281. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17282. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17283. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17284. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17285. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17286. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17287. ];
  17288. /** Gets the list of created engines */
  17289. Engine.Instances = new Array();
  17290. // Const statics
  17291. Engine._ALPHA_DISABLE = 0;
  17292. Engine._ALPHA_ADD = 1;
  17293. Engine._ALPHA_COMBINE = 2;
  17294. Engine._ALPHA_SUBTRACT = 3;
  17295. Engine._ALPHA_MULTIPLY = 4;
  17296. Engine._ALPHA_MAXIMIZED = 5;
  17297. Engine._ALPHA_ONEONE = 6;
  17298. Engine._ALPHA_PREMULTIPLIED = 7;
  17299. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17300. Engine._ALPHA_INTERPOLATE = 9;
  17301. Engine._ALPHA_SCREENMODE = 10;
  17302. Engine._DELAYLOADSTATE_NONE = 0;
  17303. Engine._DELAYLOADSTATE_LOADED = 1;
  17304. Engine._DELAYLOADSTATE_LOADING = 2;
  17305. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17306. Engine._TEXTUREFORMAT_ALPHA = 0;
  17307. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17308. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17309. Engine._TEXTUREFORMAT_RGB = 4;
  17310. Engine._TEXTUREFORMAT_RGBA = 5;
  17311. Engine._TEXTUREFORMAT_R32F = 6;
  17312. Engine._TEXTUREFORMAT_RG32F = 7;
  17313. Engine._TEXTUREFORMAT_RGB32F = 8;
  17314. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17315. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17316. Engine._TEXTURETYPE_FLOAT = 1;
  17317. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17318. // Depht or Stencil test Constants.
  17319. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17320. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17321. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17322. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17323. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17324. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17325. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17326. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17327. // Stencil Actions Constants.
  17328. Engine._KEEP = 0x1E00;
  17329. Engine._REPLACE = 0x1E01;
  17330. Engine._INCR = 0x1E02;
  17331. Engine._DECR = 0x1E03;
  17332. Engine._INVERT = 0x150A;
  17333. Engine._INCR_WRAP = 0x8507;
  17334. Engine._DECR_WRAP = 0x8508;
  17335. // Texture rescaling mode
  17336. Engine._SCALEMODE_FLOOR = 1;
  17337. Engine._SCALEMODE_NEAREST = 2;
  17338. Engine._SCALEMODE_CEILING = 3;
  17339. // Updatable statics so stick with vars here
  17340. /**
  17341. * Gets or sets the epsilon value used by collision engine
  17342. */
  17343. Engine.CollisionsEpsilon = 0.001;
  17344. /**
  17345. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17346. */
  17347. Engine.CodeRepository = "src/";
  17348. /**
  17349. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17350. */
  17351. Engine.ShadersRepository = "src/Shaders/";
  17352. return Engine;
  17353. }());
  17354. BABYLON.Engine = Engine;
  17355. })(BABYLON || (BABYLON = {}));
  17356. //# sourceMappingURL=babylon.engine.js.map
  17357. var BABYLON;
  17358. (function (BABYLON) {
  17359. /**
  17360. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17361. */
  17362. var Node = /** @class */ (function () {
  17363. /**
  17364. * Creates a new Node
  17365. * @param {string} name - the name and id to be given to this node
  17366. * @param {BABYLON.Scene} the scene this node will be added to
  17367. */
  17368. function Node(name, scene) {
  17369. if (scene === void 0) { scene = null; }
  17370. /**
  17371. * Gets or sets a string used to store user defined state for the node
  17372. */
  17373. this.state = "";
  17374. /**
  17375. * Gets or sets an object used to store user defined information for the node
  17376. */
  17377. this.metadata = null;
  17378. /**
  17379. * Gets or sets a boolean used to define if the node must be serialized
  17380. */
  17381. this.doNotSerialize = false;
  17382. /** @hidden */
  17383. this._isDisposed = false;
  17384. /**
  17385. * Gets a list of Animations associated with the node
  17386. */
  17387. this.animations = new Array();
  17388. this._ranges = {};
  17389. this._isEnabled = true;
  17390. this._isReady = true;
  17391. /** @hidden */
  17392. this._currentRenderId = -1;
  17393. this._parentRenderId = -1;
  17394. this._childRenderId = -1;
  17395. this._animationPropertiesOverride = null;
  17396. /**
  17397. * An event triggered when the mesh is disposed
  17398. */
  17399. this.onDisposeObservable = new BABYLON.Observable();
  17400. // Behaviors
  17401. this._behaviors = new Array();
  17402. this.name = name;
  17403. this.id = name;
  17404. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17405. this.uniqueId = this._scene.getUniqueId();
  17406. this._initCache();
  17407. }
  17408. /**
  17409. * Gets a boolean indicating if the node has been disposed
  17410. * @returns true if the node was disposed
  17411. */
  17412. Node.prototype.isDisposed = function () {
  17413. return this._isDisposed;
  17414. };
  17415. Object.defineProperty(Node.prototype, "parent", {
  17416. get: function () {
  17417. return this._parentNode;
  17418. },
  17419. /**
  17420. * Gets or sets the parent of the node
  17421. */
  17422. set: function (parent) {
  17423. if (this._parentNode === parent) {
  17424. return;
  17425. }
  17426. // Remove self from list of children of parent
  17427. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17428. var index = this._parentNode._children.indexOf(this);
  17429. if (index !== -1) {
  17430. this._parentNode._children.splice(index, 1);
  17431. }
  17432. }
  17433. // Store new parent
  17434. this._parentNode = parent;
  17435. // Add as child to new parent
  17436. if (this._parentNode) {
  17437. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17438. this._parentNode._children = new Array();
  17439. }
  17440. this._parentNode._children.push(this);
  17441. }
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17447. /**
  17448. * Gets or sets the animation properties override
  17449. */
  17450. get: function () {
  17451. if (!this._animationPropertiesOverride) {
  17452. return this._scene.animationPropertiesOverride;
  17453. }
  17454. return this._animationPropertiesOverride;
  17455. },
  17456. set: function (value) {
  17457. this._animationPropertiesOverride = value;
  17458. },
  17459. enumerable: true,
  17460. configurable: true
  17461. });
  17462. /**
  17463. * Gets a string idenfifying the name of the class
  17464. * @returns "Node" string
  17465. */
  17466. Node.prototype.getClassName = function () {
  17467. return "Node";
  17468. };
  17469. Object.defineProperty(Node.prototype, "onDispose", {
  17470. /**
  17471. * Sets a callback that will be raised when the node will be disposed
  17472. */
  17473. set: function (callback) {
  17474. if (this._onDisposeObserver) {
  17475. this.onDisposeObservable.remove(this._onDisposeObserver);
  17476. }
  17477. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17478. },
  17479. enumerable: true,
  17480. configurable: true
  17481. });
  17482. /**
  17483. * Gets the scene of the node
  17484. * @returns a {BABYLON.Scene}
  17485. */
  17486. Node.prototype.getScene = function () {
  17487. return this._scene;
  17488. };
  17489. /**
  17490. * Gets the engine of the node
  17491. * @returns a {BABYLON.Engine}
  17492. */
  17493. Node.prototype.getEngine = function () {
  17494. return this._scene.getEngine();
  17495. };
  17496. /**
  17497. * Attach a behavior to the node
  17498. * @see http://doc.babylonjs.com/features/behaviour
  17499. * @param behavior defines the behavior to attach
  17500. * @returns the current Node
  17501. */
  17502. Node.prototype.addBehavior = function (behavior) {
  17503. var _this = this;
  17504. var index = this._behaviors.indexOf(behavior);
  17505. if (index !== -1) {
  17506. return this;
  17507. }
  17508. behavior.init();
  17509. if (this._scene.isLoading) {
  17510. // We defer the attach when the scene will be loaded
  17511. var observer = this._scene.onDataLoadedObservable.add(function () {
  17512. behavior.attach(_this);
  17513. setTimeout(function () {
  17514. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17515. _this._scene.onDataLoadedObservable.remove(observer);
  17516. }, 0);
  17517. });
  17518. }
  17519. else {
  17520. behavior.attach(this);
  17521. }
  17522. this._behaviors.push(behavior);
  17523. return this;
  17524. };
  17525. /**
  17526. * Remove an attached behavior
  17527. * @see http://doc.babylonjs.com/features/behaviour
  17528. * @param behavior defines the behavior to attach
  17529. * @returns the current Node
  17530. */
  17531. Node.prototype.removeBehavior = function (behavior) {
  17532. var index = this._behaviors.indexOf(behavior);
  17533. if (index === -1) {
  17534. return this;
  17535. }
  17536. this._behaviors[index].detach();
  17537. this._behaviors.splice(index, 1);
  17538. return this;
  17539. };
  17540. Object.defineProperty(Node.prototype, "behaviors", {
  17541. /**
  17542. * Gets the list of attached behaviors
  17543. * @see http://doc.babylonjs.com/features/behaviour
  17544. */
  17545. get: function () {
  17546. return this._behaviors;
  17547. },
  17548. enumerable: true,
  17549. configurable: true
  17550. });
  17551. /**
  17552. * Gets an attached behavior by name
  17553. * @param name defines the name of the behavior to look for
  17554. * @see http://doc.babylonjs.com/features/behaviour
  17555. * @returns null if behavior was not found else the requested behavior
  17556. */
  17557. Node.prototype.getBehaviorByName = function (name) {
  17558. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17559. var behavior = _a[_i];
  17560. if (behavior.name === name) {
  17561. return behavior;
  17562. }
  17563. }
  17564. return null;
  17565. };
  17566. /**
  17567. * Returns the world matrix of the node
  17568. * @returns a matrix containing the node's world matrix
  17569. */
  17570. Node.prototype.getWorldMatrix = function () {
  17571. return BABYLON.Matrix.Identity();
  17572. };
  17573. /** @hidden */
  17574. Node.prototype._getWorldMatrixDeterminant = function () {
  17575. return 1;
  17576. };
  17577. // override it in derived class if you add new variables to the cache
  17578. // and call the parent class method
  17579. /** @hidden */
  17580. Node.prototype._initCache = function () {
  17581. this._cache = {};
  17582. this._cache.parent = undefined;
  17583. };
  17584. /** @hidden */
  17585. Node.prototype.updateCache = function (force) {
  17586. if (!force && this.isSynchronized())
  17587. return;
  17588. this._cache.parent = this.parent;
  17589. this._updateCache();
  17590. };
  17591. // override it in derived class if you add new variables to the cache
  17592. // and call the parent class method if !ignoreParentClass
  17593. /** @hidden */
  17594. Node.prototype._updateCache = function (ignoreParentClass) {
  17595. };
  17596. // override it in derived class if you add new variables to the cache
  17597. /** @hidden */
  17598. Node.prototype._isSynchronized = function () {
  17599. return true;
  17600. };
  17601. /** @hidden */
  17602. Node.prototype._markSyncedWithParent = function () {
  17603. if (this.parent) {
  17604. this._parentRenderId = this.parent._childRenderId;
  17605. }
  17606. };
  17607. /** @hidden */
  17608. Node.prototype.isSynchronizedWithParent = function () {
  17609. if (!this.parent) {
  17610. return true;
  17611. }
  17612. if (this._parentRenderId !== this.parent._childRenderId) {
  17613. return false;
  17614. }
  17615. return this.parent.isSynchronized();
  17616. };
  17617. /** @hidden */
  17618. Node.prototype.isSynchronized = function (updateCache) {
  17619. var check = this.hasNewParent();
  17620. check = check || !this.isSynchronizedWithParent();
  17621. check = check || !this._isSynchronized();
  17622. if (updateCache)
  17623. this.updateCache(true);
  17624. return !check;
  17625. };
  17626. /** @hidden */
  17627. Node.prototype.hasNewParent = function (update) {
  17628. if (this._cache.parent === this.parent)
  17629. return false;
  17630. if (update)
  17631. this._cache.parent = this.parent;
  17632. return true;
  17633. };
  17634. /**
  17635. * Is this node ready to be used/rendered
  17636. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17637. * @return true if the node is ready
  17638. */
  17639. Node.prototype.isReady = function (completeCheck) {
  17640. if (completeCheck === void 0) { completeCheck = false; }
  17641. return this._isReady;
  17642. };
  17643. /**
  17644. * Is this node enabled?
  17645. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  17646. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  17647. * @return whether this node (and its parent) is enabled
  17648. */
  17649. Node.prototype.isEnabled = function (checkAncestors) {
  17650. if (checkAncestors === void 0) { checkAncestors = true; }
  17651. if (checkAncestors === false) {
  17652. return this._isEnabled;
  17653. }
  17654. if (this._isEnabled === false) {
  17655. return false;
  17656. }
  17657. if (this.parent !== undefined && this.parent !== null) {
  17658. return this.parent.isEnabled(checkAncestors);
  17659. }
  17660. return true;
  17661. };
  17662. /**
  17663. * Set the enabled state of this node
  17664. * @param value defines the new enabled state
  17665. */
  17666. Node.prototype.setEnabled = function (value) {
  17667. this._isEnabled = value;
  17668. };
  17669. /**
  17670. * Is this node a descendant of the given node?
  17671. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17672. * @param ancestor defines the parent node to inspect
  17673. * @returns a boolean indicating if this node is a descendant of the given node
  17674. */
  17675. Node.prototype.isDescendantOf = function (ancestor) {
  17676. if (this.parent) {
  17677. if (this.parent === ancestor) {
  17678. return true;
  17679. }
  17680. return this.parent.isDescendantOf(ancestor);
  17681. }
  17682. return false;
  17683. };
  17684. /** @hidden */
  17685. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17686. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17687. if (!this._children) {
  17688. return;
  17689. }
  17690. for (var index = 0; index < this._children.length; index++) {
  17691. var item = this._children[index];
  17692. if (!predicate || predicate(item)) {
  17693. results.push(item);
  17694. }
  17695. if (!directDescendantsOnly) {
  17696. item._getDescendants(results, false, predicate);
  17697. }
  17698. }
  17699. };
  17700. /**
  17701. * Will return all nodes that have this node as ascendant
  17702. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17703. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17704. * @return all children nodes of all types
  17705. */
  17706. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17707. var results = new Array();
  17708. this._getDescendants(results, directDescendantsOnly, predicate);
  17709. return results;
  17710. };
  17711. /**
  17712. * Get all child-meshes of this node
  17713. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17714. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17715. * @returns an array of {BABYLON.AbstractMesh}
  17716. */
  17717. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17718. var results = [];
  17719. this._getDescendants(results, directDescendantsOnly, function (node) {
  17720. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17721. });
  17722. return results;
  17723. };
  17724. /**
  17725. * Get all child-transformNodes of this node
  17726. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17727. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17728. * @returns an array of {BABYLON.TransformNode}
  17729. */
  17730. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17731. var results = [];
  17732. this._getDescendants(results, directDescendantsOnly, function (node) {
  17733. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17734. });
  17735. return results;
  17736. };
  17737. /**
  17738. * Get all direct children of this node
  17739. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17740. * @returns an array of {BABYLON.Node}
  17741. */
  17742. Node.prototype.getChildren = function (predicate) {
  17743. return this.getDescendants(true, predicate);
  17744. };
  17745. /** @hidden */
  17746. Node.prototype._setReady = function (state) {
  17747. if (state === this._isReady) {
  17748. return;
  17749. }
  17750. if (!state) {
  17751. this._isReady = false;
  17752. return;
  17753. }
  17754. if (this.onReady) {
  17755. this.onReady(this);
  17756. }
  17757. this._isReady = true;
  17758. };
  17759. /**
  17760. * Get an animation by name
  17761. * @param name defines the name of the animation to look for
  17762. * @returns null if not found else the requested animation
  17763. */
  17764. Node.prototype.getAnimationByName = function (name) {
  17765. for (var i = 0; i < this.animations.length; i++) {
  17766. var animation = this.animations[i];
  17767. if (animation.name === name) {
  17768. return animation;
  17769. }
  17770. }
  17771. return null;
  17772. };
  17773. /**
  17774. * Creates an animation range for this node
  17775. * @param name defines the name of the range
  17776. * @param from defines the starting key
  17777. * @param to defines the end key
  17778. */
  17779. Node.prototype.createAnimationRange = function (name, from, to) {
  17780. // check name not already in use
  17781. if (!this._ranges[name]) {
  17782. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17783. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17784. if (this.animations[i]) {
  17785. this.animations[i].createRange(name, from, to);
  17786. }
  17787. }
  17788. }
  17789. };
  17790. /**
  17791. * Delete a specific animation range
  17792. * @param name defines the name of the range to delete
  17793. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17794. */
  17795. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17796. if (deleteFrames === void 0) { deleteFrames = true; }
  17797. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17798. if (this.animations[i]) {
  17799. this.animations[i].deleteRange(name, deleteFrames);
  17800. }
  17801. }
  17802. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17803. };
  17804. /**
  17805. * Get an animation range by name
  17806. * @param name defines the name of the animation range to look for
  17807. * @returns null if not found else the requested animation range
  17808. */
  17809. Node.prototype.getAnimationRange = function (name) {
  17810. return this._ranges[name];
  17811. };
  17812. /**
  17813. * Will start the animation sequence
  17814. * @param name defines the range frames for animation sequence
  17815. * @param loop defines if the animation should loop (false by default)
  17816. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17817. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17818. * @returns the object created for this animation. If range does not exist, it will return null
  17819. */
  17820. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17821. var range = this.getAnimationRange(name);
  17822. if (!range) {
  17823. return null;
  17824. }
  17825. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17826. };
  17827. /**
  17828. * Serialize animation ranges into a JSON compatible object
  17829. * @returns serialization object
  17830. */
  17831. Node.prototype.serializeAnimationRanges = function () {
  17832. var serializationRanges = [];
  17833. for (var name in this._ranges) {
  17834. var localRange = this._ranges[name];
  17835. if (!localRange) {
  17836. continue;
  17837. }
  17838. var range = {};
  17839. range.name = name;
  17840. range.from = localRange.from;
  17841. range.to = localRange.to;
  17842. serializationRanges.push(range);
  17843. }
  17844. return serializationRanges;
  17845. };
  17846. /**
  17847. * Computes the world matrix of the node
  17848. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17849. * @returns the world matrix
  17850. */
  17851. Node.prototype.computeWorldMatrix = function (force) {
  17852. return BABYLON.Matrix.Identity();
  17853. };
  17854. /**
  17855. * Releases resources associated with this node.
  17856. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17857. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17858. */
  17859. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17860. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17861. if (!doNotRecurse) {
  17862. var nodes = this.getDescendants(true);
  17863. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17864. var node = nodes_1[_i];
  17865. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17866. }
  17867. }
  17868. else {
  17869. var transformNodes = this.getChildTransformNodes(true);
  17870. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17871. var transformNode = transformNodes_1[_a];
  17872. transformNode.parent = null;
  17873. transformNode.computeWorldMatrix(true);
  17874. }
  17875. }
  17876. this.parent = null;
  17877. // Callback
  17878. this.onDisposeObservable.notifyObservers(this);
  17879. this.onDisposeObservable.clear();
  17880. // Behaviors
  17881. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17882. var behavior = _c[_b];
  17883. behavior.detach();
  17884. }
  17885. this._behaviors = [];
  17886. this._isDisposed = true;
  17887. };
  17888. /**
  17889. * Parse animation range data from a serialization object and store them into a given node
  17890. * @param node defines where to store the animation ranges
  17891. * @param parsedNode defines the serialization object to read data from
  17892. * @param scene defines the hosting scene
  17893. */
  17894. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17895. if (parsedNode.ranges) {
  17896. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17897. var data = parsedNode.ranges[index];
  17898. node.createAnimationRange(data.name, data.from, data.to);
  17899. }
  17900. }
  17901. };
  17902. __decorate([
  17903. BABYLON.serialize()
  17904. ], Node.prototype, "name", void 0);
  17905. __decorate([
  17906. BABYLON.serialize()
  17907. ], Node.prototype, "id", void 0);
  17908. __decorate([
  17909. BABYLON.serialize()
  17910. ], Node.prototype, "uniqueId", void 0);
  17911. __decorate([
  17912. BABYLON.serialize()
  17913. ], Node.prototype, "state", void 0);
  17914. __decorate([
  17915. BABYLON.serialize()
  17916. ], Node.prototype, "metadata", void 0);
  17917. return Node;
  17918. }());
  17919. BABYLON.Node = Node;
  17920. })(BABYLON || (BABYLON = {}));
  17921. //# sourceMappingURL=babylon.node.js.map
  17922. var BABYLON;
  17923. (function (BABYLON) {
  17924. var BoundingSphere = /** @class */ (function () {
  17925. /**
  17926. * Creates a new bounding sphere
  17927. * @param min defines the minimum vector (in local space)
  17928. * @param max defines the maximum vector (in local space)
  17929. */
  17930. function BoundingSphere(min, max) {
  17931. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17932. this.reConstruct(min, max);
  17933. }
  17934. /**
  17935. * Recreates the entire bounding sphere from scratch
  17936. * @param min defines the new minimum vector (in local space)
  17937. * @param max defines the new maximum vector (in local space)
  17938. */
  17939. BoundingSphere.prototype.reConstruct = function (min, max) {
  17940. this.minimum = min.clone();
  17941. this.maximum = max.clone();
  17942. var distance = BABYLON.Vector3.Distance(min, max);
  17943. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17944. this.radius = distance * 0.5;
  17945. this.centerWorld = BABYLON.Vector3.Zero();
  17946. this._update(BABYLON.Matrix.Identity());
  17947. };
  17948. // Methods
  17949. BoundingSphere.prototype._update = function (world) {
  17950. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17951. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17952. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17953. };
  17954. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17955. for (var i = 0; i < 6; i++) {
  17956. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17957. return false;
  17958. }
  17959. return true;
  17960. };
  17961. BoundingSphere.prototype.intersectsPoint = function (point) {
  17962. var x = this.centerWorld.x - point.x;
  17963. var y = this.centerWorld.y - point.y;
  17964. var z = this.centerWorld.z - point.z;
  17965. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17966. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17967. return false;
  17968. return true;
  17969. };
  17970. // Statics
  17971. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17972. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17973. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17974. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17975. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17976. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17977. return false;
  17978. return true;
  17979. };
  17980. return BoundingSphere;
  17981. }());
  17982. BABYLON.BoundingSphere = BoundingSphere;
  17983. })(BABYLON || (BABYLON = {}));
  17984. //# sourceMappingURL=babylon.boundingSphere.js.map
  17985. var BABYLON;
  17986. (function (BABYLON) {
  17987. var BoundingBox = /** @class */ (function () {
  17988. /**
  17989. * Creates a new bounding box
  17990. * @param min defines the minimum vector (in local space)
  17991. * @param max defines the maximum vector (in local space)
  17992. */
  17993. function BoundingBox(min, max) {
  17994. this.vectorsWorld = new Array();
  17995. this.reConstruct(min, max);
  17996. }
  17997. // Methods
  17998. /**
  17999. * Recreates the entire bounding box from scratch
  18000. * @param min defines the new minimum vector (in local space)
  18001. * @param max defines the new maximum vector (in local space)
  18002. */
  18003. BoundingBox.prototype.reConstruct = function (min, max) {
  18004. this.minimum = min.clone();
  18005. this.maximum = max.clone();
  18006. // Bounding vectors
  18007. this.vectors = new Array();
  18008. this.vectors.push(this.minimum.clone());
  18009. this.vectors.push(this.maximum.clone());
  18010. this.vectors.push(this.minimum.clone());
  18011. this.vectors[2].x = this.maximum.x;
  18012. this.vectors.push(this.minimum.clone());
  18013. this.vectors[3].y = this.maximum.y;
  18014. this.vectors.push(this.minimum.clone());
  18015. this.vectors[4].z = this.maximum.z;
  18016. this.vectors.push(this.maximum.clone());
  18017. this.vectors[5].z = this.minimum.z;
  18018. this.vectors.push(this.maximum.clone());
  18019. this.vectors[6].x = this.minimum.x;
  18020. this.vectors.push(this.maximum.clone());
  18021. this.vectors[7].y = this.minimum.y;
  18022. // OBB
  18023. this.center = this.maximum.add(this.minimum).scale(0.5);
  18024. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18025. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18026. // World
  18027. for (var index = 0; index < this.vectors.length; index++) {
  18028. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18029. }
  18030. this.minimumWorld = BABYLON.Vector3.Zero();
  18031. this.maximumWorld = BABYLON.Vector3.Zero();
  18032. this.centerWorld = BABYLON.Vector3.Zero();
  18033. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18034. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18035. };
  18036. BoundingBox.prototype.getWorldMatrix = function () {
  18037. return this._worldMatrix;
  18038. };
  18039. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18040. this._worldMatrix.copyFrom(matrix);
  18041. return this;
  18042. };
  18043. BoundingBox.prototype._update = function (world) {
  18044. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18045. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18046. for (var index = 0; index < this.vectors.length; index++) {
  18047. var v = this.vectorsWorld[index];
  18048. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18049. if (v.x < this.minimumWorld.x)
  18050. this.minimumWorld.x = v.x;
  18051. if (v.y < this.minimumWorld.y)
  18052. this.minimumWorld.y = v.y;
  18053. if (v.z < this.minimumWorld.z)
  18054. this.minimumWorld.z = v.z;
  18055. if (v.x > this.maximumWorld.x)
  18056. this.maximumWorld.x = v.x;
  18057. if (v.y > this.maximumWorld.y)
  18058. this.maximumWorld.y = v.y;
  18059. if (v.z > this.maximumWorld.z)
  18060. this.maximumWorld.z = v.z;
  18061. }
  18062. // Extend
  18063. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18064. this.extendSizeWorld.scaleInPlace(0.5);
  18065. // OBB
  18066. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18067. this.centerWorld.scaleInPlace(0.5);
  18068. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18069. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18070. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18071. this._worldMatrix = world;
  18072. };
  18073. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18074. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18075. };
  18076. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18077. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18078. };
  18079. BoundingBox.prototype.intersectsPoint = function (point) {
  18080. var delta = -BABYLON.Epsilon;
  18081. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18082. return false;
  18083. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18084. return false;
  18085. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18086. return false;
  18087. return true;
  18088. };
  18089. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18090. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18091. };
  18092. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18093. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18094. return false;
  18095. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18096. return false;
  18097. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18098. return false;
  18099. return true;
  18100. };
  18101. // Statics
  18102. BoundingBox.Intersects = function (box0, box1) {
  18103. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18104. return false;
  18105. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18106. return false;
  18107. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18108. return false;
  18109. return true;
  18110. };
  18111. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18112. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18113. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18114. return (num <= (sphereRadius * sphereRadius));
  18115. };
  18116. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18117. for (var p = 0; p < 6; p++) {
  18118. for (var i = 0; i < 8; i++) {
  18119. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18120. return false;
  18121. }
  18122. }
  18123. }
  18124. return true;
  18125. };
  18126. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18127. for (var p = 0; p < 6; p++) {
  18128. var inCount = 8;
  18129. for (var i = 0; i < 8; i++) {
  18130. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18131. --inCount;
  18132. }
  18133. else {
  18134. break;
  18135. }
  18136. }
  18137. if (inCount === 0)
  18138. return false;
  18139. }
  18140. return true;
  18141. };
  18142. return BoundingBox;
  18143. }());
  18144. BABYLON.BoundingBox = BoundingBox;
  18145. })(BABYLON || (BABYLON = {}));
  18146. //# sourceMappingURL=babylon.boundingBox.js.map
  18147. var BABYLON;
  18148. (function (BABYLON) {
  18149. var computeBoxExtents = function (axis, box) {
  18150. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18151. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18152. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18153. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18154. var r = r0 + r1 + r2;
  18155. return {
  18156. min: p - r,
  18157. max: p + r
  18158. };
  18159. };
  18160. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18161. var axisOverlap = function (axis, box0, box1) {
  18162. var result0 = computeBoxExtents(axis, box0);
  18163. var result1 = computeBoxExtents(axis, box1);
  18164. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18165. };
  18166. var BoundingInfo = /** @class */ (function () {
  18167. function BoundingInfo(minimum, maximum) {
  18168. this.minimum = minimum;
  18169. this.maximum = maximum;
  18170. this._isLocked = false;
  18171. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18172. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18173. }
  18174. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18175. get: function () {
  18176. return this._isLocked;
  18177. },
  18178. set: function (value) {
  18179. this._isLocked = value;
  18180. },
  18181. enumerable: true,
  18182. configurable: true
  18183. });
  18184. // Methods
  18185. BoundingInfo.prototype.update = function (world) {
  18186. if (this._isLocked) {
  18187. return;
  18188. }
  18189. this.boundingBox._update(world);
  18190. this.boundingSphere._update(world);
  18191. };
  18192. /**
  18193. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18194. * @param center New center of the bounding info
  18195. * @param extend New extend of the bounding info
  18196. */
  18197. BoundingInfo.prototype.centerOn = function (center, extend) {
  18198. this.minimum = center.subtract(extend);
  18199. this.maximum = center.add(extend);
  18200. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18201. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18202. return this;
  18203. };
  18204. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18205. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18206. return false;
  18207. return this.boundingBox.isInFrustum(frustumPlanes);
  18208. };
  18209. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18210. /**
  18211. * Gets the world distance between the min and max points of the bounding box
  18212. */
  18213. get: function () {
  18214. var boundingBox = this.boundingBox;
  18215. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18216. return size.length();
  18217. },
  18218. enumerable: true,
  18219. configurable: true
  18220. });
  18221. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18222. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18223. };
  18224. BoundingInfo.prototype._checkCollision = function (collider) {
  18225. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18226. };
  18227. BoundingInfo.prototype.intersectsPoint = function (point) {
  18228. if (!this.boundingSphere.centerWorld) {
  18229. return false;
  18230. }
  18231. if (!this.boundingSphere.intersectsPoint(point)) {
  18232. return false;
  18233. }
  18234. if (!this.boundingBox.intersectsPoint(point)) {
  18235. return false;
  18236. }
  18237. return true;
  18238. };
  18239. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18240. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18241. return false;
  18242. }
  18243. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18244. return false;
  18245. }
  18246. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18247. return false;
  18248. }
  18249. if (!precise) {
  18250. return true;
  18251. }
  18252. var box0 = this.boundingBox;
  18253. var box1 = boundingInfo.boundingBox;
  18254. if (!axisOverlap(box0.directions[0], box0, box1))
  18255. return false;
  18256. if (!axisOverlap(box0.directions[1], box0, box1))
  18257. return false;
  18258. if (!axisOverlap(box0.directions[2], box0, box1))
  18259. return false;
  18260. if (!axisOverlap(box1.directions[0], box0, box1))
  18261. return false;
  18262. if (!axisOverlap(box1.directions[1], box0, box1))
  18263. return false;
  18264. if (!axisOverlap(box1.directions[2], box0, box1))
  18265. return false;
  18266. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18267. return false;
  18268. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18269. return false;
  18270. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18271. return false;
  18272. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18273. return false;
  18274. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18275. return false;
  18276. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18277. return false;
  18278. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18279. return false;
  18280. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18281. return false;
  18282. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18283. return false;
  18284. return true;
  18285. };
  18286. return BoundingInfo;
  18287. }());
  18288. BABYLON.BoundingInfo = BoundingInfo;
  18289. })(BABYLON || (BABYLON = {}));
  18290. //# sourceMappingURL=babylon.boundingInfo.js.map
  18291. var BABYLON;
  18292. (function (BABYLON) {
  18293. var TransformNode = /** @class */ (function (_super) {
  18294. __extends(TransformNode, _super);
  18295. function TransformNode(name, scene, isPure) {
  18296. if (scene === void 0) { scene = null; }
  18297. if (isPure === void 0) { isPure = true; }
  18298. var _this = _super.call(this, name, scene) || this;
  18299. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18300. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18301. _this._up = new BABYLON.Vector3(0, 1, 0);
  18302. _this._right = new BABYLON.Vector3(1, 0, 0);
  18303. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18304. // Properties
  18305. _this._rotation = BABYLON.Vector3.Zero();
  18306. _this._scaling = BABYLON.Vector3.One();
  18307. _this._isDirty = false;
  18308. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18309. _this.scalingDeterminant = 1;
  18310. _this.infiniteDistance = false;
  18311. _this.position = BABYLON.Vector3.Zero();
  18312. _this._localWorld = BABYLON.Matrix.Zero();
  18313. _this._worldMatrix = BABYLON.Matrix.Zero();
  18314. _this._worldMatrixDeterminant = 0;
  18315. _this._absolutePosition = BABYLON.Vector3.Zero();
  18316. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18317. _this._postMultiplyPivotMatrix = false;
  18318. _this._isWorldMatrixFrozen = false;
  18319. /**
  18320. * An event triggered after the world matrix is updated
  18321. */
  18322. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18323. _this._nonUniformScaling = false;
  18324. if (isPure) {
  18325. _this.getScene().addTransformNode(_this);
  18326. }
  18327. return _this;
  18328. }
  18329. /**
  18330. * Gets a string idenfifying the name of the class
  18331. * @returns "TransformNode" string
  18332. */
  18333. TransformNode.prototype.getClassName = function () {
  18334. return "TransformNode";
  18335. };
  18336. Object.defineProperty(TransformNode.prototype, "rotation", {
  18337. /**
  18338. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18339. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18340. * Default : (0.0, 0.0, 0.0)
  18341. */
  18342. get: function () {
  18343. return this._rotation;
  18344. },
  18345. set: function (newRotation) {
  18346. this._rotation = newRotation;
  18347. },
  18348. enumerable: true,
  18349. configurable: true
  18350. });
  18351. Object.defineProperty(TransformNode.prototype, "scaling", {
  18352. /**
  18353. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18354. * Default : (1.0, 1.0, 1.0)
  18355. */
  18356. get: function () {
  18357. return this._scaling;
  18358. },
  18359. /**
  18360. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18361. * Default : (1.0, 1.0, 1.0)
  18362. */
  18363. set: function (newScaling) {
  18364. this._scaling = newScaling;
  18365. },
  18366. enumerable: true,
  18367. configurable: true
  18368. });
  18369. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18370. /**
  18371. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18372. * It's null by default.
  18373. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18374. */
  18375. get: function () {
  18376. return this._rotationQuaternion;
  18377. },
  18378. set: function (quaternion) {
  18379. this._rotationQuaternion = quaternion;
  18380. //reset the rotation vector.
  18381. if (quaternion && this.rotation.length()) {
  18382. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18383. }
  18384. },
  18385. enumerable: true,
  18386. configurable: true
  18387. });
  18388. Object.defineProperty(TransformNode.prototype, "forward", {
  18389. /**
  18390. * The forward direction of that transform in world space.
  18391. */
  18392. get: function () {
  18393. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18394. },
  18395. enumerable: true,
  18396. configurable: true
  18397. });
  18398. Object.defineProperty(TransformNode.prototype, "up", {
  18399. /**
  18400. * The up direction of that transform in world space.
  18401. */
  18402. get: function () {
  18403. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18404. },
  18405. enumerable: true,
  18406. configurable: true
  18407. });
  18408. Object.defineProperty(TransformNode.prototype, "right", {
  18409. /**
  18410. * The right direction of that transform in world space.
  18411. */
  18412. get: function () {
  18413. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18414. },
  18415. enumerable: true,
  18416. configurable: true
  18417. });
  18418. /**
  18419. * Returns the latest update of the World matrix
  18420. * Returns a Matrix.
  18421. */
  18422. TransformNode.prototype.getWorldMatrix = function () {
  18423. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18424. this.computeWorldMatrix();
  18425. }
  18426. return this._worldMatrix;
  18427. };
  18428. /** @hidden */
  18429. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18430. return this._worldMatrixDeterminant;
  18431. };
  18432. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18433. /**
  18434. * Returns directly the latest state of the mesh World matrix.
  18435. * A Matrix is returned.
  18436. */
  18437. get: function () {
  18438. return this._worldMatrix;
  18439. },
  18440. enumerable: true,
  18441. configurable: true
  18442. });
  18443. /**
  18444. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18445. * Returns the TransformNode.
  18446. */
  18447. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18448. this._poseMatrix.copyFrom(matrix);
  18449. return this;
  18450. };
  18451. /**
  18452. * Returns the mesh Pose matrix.
  18453. * Returned object : Matrix
  18454. */
  18455. TransformNode.prototype.getPoseMatrix = function () {
  18456. return this._poseMatrix;
  18457. };
  18458. TransformNode.prototype._isSynchronized = function () {
  18459. if (this._isDirty) {
  18460. return false;
  18461. }
  18462. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18463. return false;
  18464. if (this._cache.pivotMatrixUpdated) {
  18465. return false;
  18466. }
  18467. if (this.infiniteDistance) {
  18468. return false;
  18469. }
  18470. if (!this._cache.position.equals(this.position))
  18471. return false;
  18472. if (this.rotationQuaternion) {
  18473. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18474. return false;
  18475. }
  18476. if (!this._cache.rotation.equals(this.rotation))
  18477. return false;
  18478. if (!this._cache.scaling.equals(this.scaling))
  18479. return false;
  18480. return true;
  18481. };
  18482. TransformNode.prototype._initCache = function () {
  18483. _super.prototype._initCache.call(this);
  18484. this._cache.localMatrixUpdated = false;
  18485. this._cache.position = BABYLON.Vector3.Zero();
  18486. this._cache.scaling = BABYLON.Vector3.Zero();
  18487. this._cache.rotation = BABYLON.Vector3.Zero();
  18488. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18489. this._cache.billboardMode = -1;
  18490. };
  18491. TransformNode.prototype.markAsDirty = function (property) {
  18492. if (property === "rotation") {
  18493. this.rotationQuaternion = null;
  18494. }
  18495. this._currentRenderId = Number.MAX_VALUE;
  18496. this._isDirty = true;
  18497. return this;
  18498. };
  18499. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18500. /**
  18501. * Returns the current mesh absolute position.
  18502. * Retuns a Vector3.
  18503. */
  18504. get: function () {
  18505. return this._absolutePosition;
  18506. },
  18507. enumerable: true,
  18508. configurable: true
  18509. });
  18510. /**
  18511. * Sets a new matrix to apply before all other transformation
  18512. * @param matrix defines the transform matrix
  18513. * @returns the current TransformNode
  18514. */
  18515. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18516. return this.setPivotMatrix(matrix, false);
  18517. };
  18518. /**
  18519. * Sets a new pivot matrix to the current node
  18520. * @param matrix defines the new pivot matrix to use
  18521. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  18522. * @returns the current TransformNode
  18523. */
  18524. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18525. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18526. this._pivotMatrix = matrix.clone();
  18527. this._cache.pivotMatrixUpdated = true;
  18528. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18529. if (this._postMultiplyPivotMatrix) {
  18530. if (!this._pivotMatrixInverse) {
  18531. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18532. }
  18533. else {
  18534. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18535. }
  18536. }
  18537. return this;
  18538. };
  18539. /**
  18540. * Returns the mesh pivot matrix.
  18541. * Default : Identity.
  18542. * A Matrix is returned.
  18543. */
  18544. TransformNode.prototype.getPivotMatrix = function () {
  18545. return this._pivotMatrix;
  18546. };
  18547. /**
  18548. * Prevents the World matrix to be computed any longer.
  18549. * Returns the TransformNode.
  18550. */
  18551. TransformNode.prototype.freezeWorldMatrix = function () {
  18552. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18553. this.computeWorldMatrix(true);
  18554. this._isWorldMatrixFrozen = true;
  18555. return this;
  18556. };
  18557. /**
  18558. * Allows back the World matrix computation.
  18559. * Returns the TransformNode.
  18560. */
  18561. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18562. this._isWorldMatrixFrozen = false;
  18563. this.computeWorldMatrix(true);
  18564. return this;
  18565. };
  18566. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18567. /**
  18568. * True if the World matrix has been frozen.
  18569. * Returns a boolean.
  18570. */
  18571. get: function () {
  18572. return this._isWorldMatrixFrozen;
  18573. },
  18574. enumerable: true,
  18575. configurable: true
  18576. });
  18577. /**
  18578. * Retuns the mesh absolute position in the World.
  18579. * Returns a Vector3.
  18580. */
  18581. TransformNode.prototype.getAbsolutePosition = function () {
  18582. this.computeWorldMatrix();
  18583. return this._absolutePosition;
  18584. };
  18585. /**
  18586. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18587. * Returns the TransformNode.
  18588. */
  18589. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18590. if (!absolutePosition) {
  18591. return this;
  18592. }
  18593. var absolutePositionX;
  18594. var absolutePositionY;
  18595. var absolutePositionZ;
  18596. if (absolutePosition.x === undefined) {
  18597. if (arguments.length < 3) {
  18598. return this;
  18599. }
  18600. absolutePositionX = arguments[0];
  18601. absolutePositionY = arguments[1];
  18602. absolutePositionZ = arguments[2];
  18603. }
  18604. else {
  18605. absolutePositionX = absolutePosition.x;
  18606. absolutePositionY = absolutePosition.y;
  18607. absolutePositionZ = absolutePosition.z;
  18608. }
  18609. if (this.parent) {
  18610. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18611. invertParentWorldMatrix.invert();
  18612. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18613. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18614. }
  18615. else {
  18616. this.position.x = absolutePositionX;
  18617. this.position.y = absolutePositionY;
  18618. this.position.z = absolutePositionZ;
  18619. }
  18620. return this;
  18621. };
  18622. /**
  18623. * Sets the mesh position in its local space.
  18624. * Returns the TransformNode.
  18625. */
  18626. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18627. this.computeWorldMatrix();
  18628. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18629. return this;
  18630. };
  18631. /**
  18632. * Returns the mesh position in the local space from the current World matrix values.
  18633. * Returns a new Vector3.
  18634. */
  18635. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18636. this.computeWorldMatrix();
  18637. var invLocalWorldMatrix = this._localWorld.clone();
  18638. invLocalWorldMatrix.invert();
  18639. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18640. };
  18641. /**
  18642. * Translates the mesh along the passed Vector3 in its local space.
  18643. * Returns the TransformNode.
  18644. */
  18645. TransformNode.prototype.locallyTranslate = function (vector3) {
  18646. this.computeWorldMatrix(true);
  18647. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18648. return this;
  18649. };
  18650. /**
  18651. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18652. * @param targetPoint the position (must be in same space as current mesh) to look at
  18653. * @param yawCor optional yaw (y-axis) correction in radians
  18654. * @param pitchCor optional pitch (x-axis) correction in radians
  18655. * @param rollCor optional roll (z-axis) correction in radians
  18656. * @param space the choosen space of the target
  18657. * @returns the TransformNode.
  18658. */
  18659. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18660. if (yawCor === void 0) { yawCor = 0; }
  18661. if (pitchCor === void 0) { pitchCor = 0; }
  18662. if (rollCor === void 0) { rollCor = 0; }
  18663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18664. var dv = TransformNode._lookAtVectorCache;
  18665. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18666. targetPoint.subtractToRef(pos, dv);
  18667. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18668. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18669. var pitch = Math.atan2(dv.y, len);
  18670. if (this.rotationQuaternion) {
  18671. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18672. }
  18673. else {
  18674. this.rotation.x = pitch + pitchCor;
  18675. this.rotation.y = yaw + yawCor;
  18676. this.rotation.z = rollCor;
  18677. }
  18678. return this;
  18679. };
  18680. /**
  18681. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18682. * This Vector3 is expressed in the World space.
  18683. */
  18684. TransformNode.prototype.getDirection = function (localAxis) {
  18685. var result = BABYLON.Vector3.Zero();
  18686. this.getDirectionToRef(localAxis, result);
  18687. return result;
  18688. };
  18689. /**
  18690. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18691. * localAxis is expressed in the mesh local space.
  18692. * result is computed in the Wordl space from the mesh World matrix.
  18693. * Returns the TransformNode.
  18694. */
  18695. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18696. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18697. return this;
  18698. };
  18699. /**
  18700. * Sets a new pivot point to the current node
  18701. * @param point defines the new pivot point to use
  18702. * @param space defines if the point is in world or local space (local by default)
  18703. * @returns the current TransformNode
  18704. */
  18705. TransformNode.prototype.setPivotPoint = function (point, space) {
  18706. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18707. if (this.getScene().getRenderId() == 0) {
  18708. this.computeWorldMatrix(true);
  18709. }
  18710. var wm = this.getWorldMatrix();
  18711. if (space == BABYLON.Space.WORLD) {
  18712. var tmat = BABYLON.Tmp.Matrix[0];
  18713. wm.invertToRef(tmat);
  18714. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18715. }
  18716. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18717. };
  18718. /**
  18719. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18720. */
  18721. TransformNode.prototype.getPivotPoint = function () {
  18722. var point = BABYLON.Vector3.Zero();
  18723. this.getPivotPointToRef(point);
  18724. return point;
  18725. };
  18726. /**
  18727. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18728. * Returns the TransformNode.
  18729. */
  18730. TransformNode.prototype.getPivotPointToRef = function (result) {
  18731. result.x = -this._pivotMatrix.m[12];
  18732. result.y = -this._pivotMatrix.m[13];
  18733. result.z = -this._pivotMatrix.m[14];
  18734. return this;
  18735. };
  18736. /**
  18737. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18738. */
  18739. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18740. var point = BABYLON.Vector3.Zero();
  18741. this.getAbsolutePivotPointToRef(point);
  18742. return point;
  18743. };
  18744. /**
  18745. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18746. * Returns the TransformNode.
  18747. */
  18748. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18749. result.x = this._pivotMatrix.m[12];
  18750. result.y = this._pivotMatrix.m[13];
  18751. result.z = this._pivotMatrix.m[14];
  18752. this.getPivotPointToRef(result);
  18753. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18754. return this;
  18755. };
  18756. /**
  18757. * Defines the passed node as the parent of the current node.
  18758. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18759. * Returns the TransformNode.
  18760. */
  18761. TransformNode.prototype.setParent = function (node) {
  18762. if (node === null) {
  18763. var rotation = BABYLON.Tmp.Quaternion[0];
  18764. var position = BABYLON.Tmp.Vector3[0];
  18765. var scale = BABYLON.Tmp.Vector3[1];
  18766. if (this.parent && this.parent.computeWorldMatrix) {
  18767. this.parent.computeWorldMatrix(true);
  18768. }
  18769. this.computeWorldMatrix(true);
  18770. this.getWorldMatrix().decompose(scale, rotation, position);
  18771. if (this.rotationQuaternion) {
  18772. this.rotationQuaternion.copyFrom(rotation);
  18773. }
  18774. else {
  18775. rotation.toEulerAnglesToRef(this.rotation);
  18776. }
  18777. this.scaling.x = scale.x;
  18778. this.scaling.y = scale.y;
  18779. this.scaling.z = scale.z;
  18780. this.position.x = position.x;
  18781. this.position.y = position.y;
  18782. this.position.z = position.z;
  18783. }
  18784. else {
  18785. var rotation = BABYLON.Tmp.Quaternion[0];
  18786. var position = BABYLON.Tmp.Vector3[0];
  18787. var scale = BABYLON.Tmp.Vector3[1];
  18788. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18789. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18790. this.computeWorldMatrix(true);
  18791. node.computeWorldMatrix(true);
  18792. node.getWorldMatrix().invertToRef(invParentMatrix);
  18793. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18794. diffMatrix.decompose(scale, rotation, position);
  18795. if (this.rotationQuaternion) {
  18796. this.rotationQuaternion.copyFrom(rotation);
  18797. }
  18798. else {
  18799. rotation.toEulerAnglesToRef(this.rotation);
  18800. }
  18801. this.position.x = position.x;
  18802. this.position.y = position.y;
  18803. this.position.z = position.z;
  18804. this.scaling.x = scale.x;
  18805. this.scaling.y = scale.y;
  18806. this.scaling.z = scale.z;
  18807. }
  18808. this.parent = node;
  18809. return this;
  18810. };
  18811. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18812. get: function () {
  18813. return this._nonUniformScaling;
  18814. },
  18815. enumerable: true,
  18816. configurable: true
  18817. });
  18818. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18819. if (this._nonUniformScaling === value) {
  18820. return false;
  18821. }
  18822. this._nonUniformScaling = true;
  18823. return true;
  18824. };
  18825. /**
  18826. * Attach the current TransformNode to another TransformNode associated with a bone
  18827. * @param bone Bone affecting the TransformNode
  18828. * @param affectedTransformNode TransformNode associated with the bone
  18829. */
  18830. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18831. this._transformToBoneReferal = affectedTransformNode;
  18832. this.parent = bone;
  18833. if (bone.getWorldMatrix().determinant() < 0) {
  18834. this.scalingDeterminant *= -1;
  18835. }
  18836. return this;
  18837. };
  18838. TransformNode.prototype.detachFromBone = function () {
  18839. if (!this.parent) {
  18840. return this;
  18841. }
  18842. if (this.parent.getWorldMatrix().determinant() < 0) {
  18843. this.scalingDeterminant *= -1;
  18844. }
  18845. this._transformToBoneReferal = null;
  18846. this.parent = null;
  18847. return this;
  18848. };
  18849. /**
  18850. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18851. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18852. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18853. * The passed axis is also normalized.
  18854. * Returns the TransformNode.
  18855. */
  18856. TransformNode.prototype.rotate = function (axis, amount, space) {
  18857. axis.normalize();
  18858. if (!this.rotationQuaternion) {
  18859. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18860. this.rotation = BABYLON.Vector3.Zero();
  18861. }
  18862. var rotationQuaternion;
  18863. if (!space || space === BABYLON.Space.LOCAL) {
  18864. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18865. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18866. }
  18867. else {
  18868. if (this.parent) {
  18869. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18870. invertParentWorldMatrix.invert();
  18871. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18872. }
  18873. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18874. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18875. }
  18876. return this;
  18877. };
  18878. /**
  18879. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18880. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18881. * The passed axis is also normalized.
  18882. * Returns the TransformNode.
  18883. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18884. */
  18885. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18886. axis.normalize();
  18887. if (!this.rotationQuaternion) {
  18888. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18889. this.rotation.copyFromFloats(0, 0, 0);
  18890. }
  18891. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18892. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18893. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18894. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18895. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18896. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18897. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18898. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18899. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18900. return this;
  18901. };
  18902. /**
  18903. * Translates the mesh along the axis vector for the passed distance in the given space.
  18904. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18905. * Returns the TransformNode.
  18906. */
  18907. TransformNode.prototype.translate = function (axis, distance, space) {
  18908. var displacementVector = axis.scale(distance);
  18909. if (!space || space === BABYLON.Space.LOCAL) {
  18910. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18911. this.setPositionWithLocalVector(tempV3);
  18912. }
  18913. else {
  18914. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18915. }
  18916. return this;
  18917. };
  18918. /**
  18919. * Adds a rotation step to the mesh current rotation.
  18920. * x, y, z are Euler angles expressed in radians.
  18921. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18922. * This means this rotation is made in the mesh local space only.
  18923. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18924. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18925. * ```javascript
  18926. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18927. * ```
  18928. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18929. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.addRotation = function (x, y, z) {
  18933. var rotationQuaternion;
  18934. if (this.rotationQuaternion) {
  18935. rotationQuaternion = this.rotationQuaternion;
  18936. }
  18937. else {
  18938. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18939. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18940. }
  18941. var accumulation = BABYLON.Tmp.Quaternion[0];
  18942. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18943. rotationQuaternion.multiplyInPlace(accumulation);
  18944. if (!this.rotationQuaternion) {
  18945. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18946. }
  18947. return this;
  18948. };
  18949. /**
  18950. * Computes the mesh World matrix and returns it.
  18951. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18952. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18953. * If the parameter `force`is set to `true`, the actual computation is done.
  18954. * Returns the mesh World Matrix.
  18955. */
  18956. TransformNode.prototype.computeWorldMatrix = function (force) {
  18957. if (this._isWorldMatrixFrozen) {
  18958. return this._worldMatrix;
  18959. }
  18960. if (!force && this.isSynchronized(true)) {
  18961. this._currentRenderId = this.getScene().getRenderId();
  18962. return this._worldMatrix;
  18963. }
  18964. this._cache.position.copyFrom(this.position);
  18965. this._cache.scaling.copyFrom(this.scaling);
  18966. this._cache.pivotMatrixUpdated = false;
  18967. this._cache.billboardMode = this.billboardMode;
  18968. this._currentRenderId = this.getScene().getRenderId();
  18969. this._childRenderId = this.getScene().getRenderId();
  18970. this._isDirty = false;
  18971. // Scaling
  18972. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18973. // Rotation
  18974. //rotate, if quaternion is set and rotation was used
  18975. if (this.rotationQuaternion) {
  18976. var len = this.rotation.length();
  18977. if (len) {
  18978. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18979. this.rotation.copyFromFloats(0, 0, 0);
  18980. }
  18981. }
  18982. if (this.rotationQuaternion) {
  18983. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18984. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18985. }
  18986. else {
  18987. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18988. this._cache.rotation.copyFrom(this.rotation);
  18989. }
  18990. // Translation
  18991. var camera = this.getScene().activeCamera;
  18992. if (this.infiniteDistance && !this.parent && camera) {
  18993. var cameraWorldMatrix = camera.getWorldMatrix();
  18994. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18995. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18996. }
  18997. else {
  18998. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18999. }
  19000. // Composing transformations
  19001. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19002. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19003. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19004. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19005. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19006. // Need to decompose each rotation here
  19007. var currentPosition = BABYLON.Tmp.Vector3[3];
  19008. if (this.parent && this.parent.getWorldMatrix) {
  19009. if (this._transformToBoneReferal) {
  19010. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19011. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19012. }
  19013. else {
  19014. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19015. }
  19016. }
  19017. else {
  19018. currentPosition.copyFrom(this.position);
  19019. }
  19020. currentPosition.subtractInPlace(camera.globalPosition);
  19021. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19022. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19023. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19024. }
  19025. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19026. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19027. }
  19028. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19029. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19030. }
  19031. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19032. }
  19033. else {
  19034. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19035. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19036. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19037. }
  19038. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19039. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19040. }
  19041. // Local world
  19042. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19043. // Parent
  19044. if (this.parent && this.parent.getWorldMatrix) {
  19045. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19046. if (this._transformToBoneReferal) {
  19047. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19048. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19049. }
  19050. else {
  19051. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19052. }
  19053. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19054. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19055. this._worldMatrix.copyFrom(this._localWorld);
  19056. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19057. }
  19058. else {
  19059. if (this._transformToBoneReferal) {
  19060. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19061. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19062. }
  19063. else {
  19064. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19065. }
  19066. }
  19067. this._markSyncedWithParent();
  19068. }
  19069. else {
  19070. this._worldMatrix.copyFrom(this._localWorld);
  19071. }
  19072. // Post multiply inverse of pivotMatrix
  19073. if (this._postMultiplyPivotMatrix) {
  19074. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19075. }
  19076. // Normal matrix
  19077. if (this.scaling.isNonUniform) {
  19078. this._updateNonUniformScalingState(true);
  19079. }
  19080. else if (this.parent && this.parent._nonUniformScaling) {
  19081. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19082. }
  19083. else {
  19084. this._updateNonUniformScalingState(false);
  19085. }
  19086. this._afterComputeWorldMatrix();
  19087. // Absolute position
  19088. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19089. // Callbacks
  19090. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19091. if (!this._poseMatrix) {
  19092. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19093. }
  19094. // Cache the determinant
  19095. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19096. return this._worldMatrix;
  19097. };
  19098. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19099. };
  19100. /**
  19101. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19102. * @param func: callback function to add
  19103. *
  19104. * Returns the TransformNode.
  19105. */
  19106. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19107. this.onAfterWorldMatrixUpdateObservable.add(func);
  19108. return this;
  19109. };
  19110. /**
  19111. * Removes a registered callback function.
  19112. * Returns the TransformNode.
  19113. */
  19114. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19115. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19116. return this;
  19117. };
  19118. /**
  19119. * Clone the current transform node
  19120. * Returns the new transform node
  19121. * @param name Name of the new clone
  19122. * @param newParent New parent for the clone
  19123. * @param doNotCloneChildren Do not clone children hierarchy
  19124. */
  19125. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19126. var _this = this;
  19127. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19128. result.name = name;
  19129. result.id = name;
  19130. if (newParent) {
  19131. result.parent = newParent;
  19132. }
  19133. if (!doNotCloneChildren) {
  19134. // Children
  19135. var directDescendants = this.getDescendants(true);
  19136. for (var index = 0; index < directDescendants.length; index++) {
  19137. var child = directDescendants[index];
  19138. if (child.clone) {
  19139. child.clone(name + "." + child.name, result);
  19140. }
  19141. }
  19142. }
  19143. return result;
  19144. };
  19145. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19146. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19147. serializationObject.type = this.getClassName();
  19148. // Parent
  19149. if (this.parent) {
  19150. serializationObject.parentId = this.parent.id;
  19151. }
  19152. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19153. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19154. }
  19155. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19156. serializationObject.isEnabled = this.isEnabled();
  19157. // Parent
  19158. if (this.parent) {
  19159. serializationObject.parentId = this.parent.id;
  19160. }
  19161. return serializationObject;
  19162. };
  19163. // Statics
  19164. /**
  19165. * Returns a new TransformNode object parsed from the source provided.
  19166. * The parameter `parsedMesh` is the source.
  19167. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19168. */
  19169. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19170. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19171. if (BABYLON.Tags) {
  19172. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19173. }
  19174. if (parsedTransformNode.localMatrix) {
  19175. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19176. }
  19177. else if (parsedTransformNode.pivotMatrix) {
  19178. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19179. }
  19180. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19181. // Parent
  19182. if (parsedTransformNode.parentId) {
  19183. transformNode._waitingParentId = parsedTransformNode.parentId;
  19184. }
  19185. return transformNode;
  19186. };
  19187. /**
  19188. * Releases resources associated with this transform node.
  19189. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19190. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19191. */
  19192. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19193. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19194. // Animations
  19195. this.getScene().stopAnimation(this);
  19196. // Remove from scene
  19197. this.getScene().removeTransformNode(this);
  19198. this.onAfterWorldMatrixUpdateObservable.clear();
  19199. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19200. };
  19201. // Statics
  19202. TransformNode.BILLBOARDMODE_NONE = 0;
  19203. TransformNode.BILLBOARDMODE_X = 1;
  19204. TransformNode.BILLBOARDMODE_Y = 2;
  19205. TransformNode.BILLBOARDMODE_Z = 4;
  19206. TransformNode.BILLBOARDMODE_ALL = 7;
  19207. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19208. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19209. __decorate([
  19210. BABYLON.serializeAsVector3()
  19211. ], TransformNode.prototype, "_rotation", void 0);
  19212. __decorate([
  19213. BABYLON.serializeAsQuaternion()
  19214. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19215. __decorate([
  19216. BABYLON.serializeAsVector3()
  19217. ], TransformNode.prototype, "_scaling", void 0);
  19218. __decorate([
  19219. BABYLON.serialize()
  19220. ], TransformNode.prototype, "billboardMode", void 0);
  19221. __decorate([
  19222. BABYLON.serialize()
  19223. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19224. __decorate([
  19225. BABYLON.serialize()
  19226. ], TransformNode.prototype, "infiniteDistance", void 0);
  19227. __decorate([
  19228. BABYLON.serializeAsVector3()
  19229. ], TransformNode.prototype, "position", void 0);
  19230. return TransformNode;
  19231. }(BABYLON.Node));
  19232. BABYLON.TransformNode = TransformNode;
  19233. })(BABYLON || (BABYLON = {}));
  19234. //# sourceMappingURL=babylon.transformNode.js.map
  19235. var BABYLON;
  19236. (function (BABYLON) {
  19237. /**
  19238. * Class used to store all common mesh properties
  19239. */
  19240. var AbstractMesh = /** @class */ (function (_super) {
  19241. __extends(AbstractMesh, _super);
  19242. // Constructor
  19243. /**
  19244. * Creates a new AbstractMesh
  19245. * @param name defines the name of the mesh
  19246. * @param scene defines the hosting scene
  19247. */
  19248. function AbstractMesh(name, scene) {
  19249. if (scene === void 0) { scene = null; }
  19250. var _this = _super.call(this, name, scene, false) || this;
  19251. _this._facetNb = 0; // facet number
  19252. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19253. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19254. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19255. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19256. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19257. _this._subDiv = {
  19258. max: 1,
  19259. X: 1,
  19260. Y: 1,
  19261. Z: 1
  19262. };
  19263. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19264. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19265. // Events
  19266. /**
  19267. * An event triggered when this mesh collides with another one
  19268. */
  19269. _this.onCollideObservable = new BABYLON.Observable();
  19270. /**
  19271. * An event triggered when the collision's position changes
  19272. */
  19273. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19274. /**
  19275. * An event triggered when material is changed
  19276. */
  19277. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19278. // Properties
  19279. /**
  19280. * Gets or sets the orientation for POV movement & rotation
  19281. */
  19282. _this.definedFacingForward = true;
  19283. /**
  19284. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19285. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19286. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19287. * @see http://doc.babylonjs.com/features/occlusionquery
  19288. */
  19289. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19290. /**
  19291. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19292. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19293. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19294. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19295. * @see http://doc.babylonjs.com/features/occlusionquery
  19296. */
  19297. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19298. /**
  19299. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19300. * The default value is -1 which means don't break the query and wait till the result
  19301. * @see http://doc.babylonjs.com/features/occlusionquery
  19302. */
  19303. _this.occlusionRetryCount = -1;
  19304. _this._occlusionInternalRetryCounter = 0;
  19305. _this._isOccluded = false;
  19306. _this._isOcclusionQueryInProgress = false;
  19307. _this._visibility = 1.0;
  19308. /** Gets or sets the alpha index used to sort transparent meshes
  19309. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19310. */
  19311. _this.alphaIndex = Number.MAX_VALUE;
  19312. /**
  19313. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19314. */
  19315. _this.isVisible = true;
  19316. /**
  19317. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19318. */
  19319. _this.isPickable = true;
  19320. /**
  19321. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19322. */
  19323. _this.showBoundingBox = false;
  19324. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19325. _this.showSubMeshesBoundingBox = false;
  19326. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19327. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19328. */
  19329. _this.isBlocker = false;
  19330. /**
  19331. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19332. */
  19333. _this.enablePointerMoveEvents = false;
  19334. /**
  19335. * Specifies the rendering group id for this mesh (0 by default)
  19336. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19337. */
  19338. _this.renderingGroupId = 0;
  19339. _this._receiveShadows = false;
  19340. /**
  19341. * Gets or sets a boolean indicating if the outline must be rendered as well
  19342. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19343. */
  19344. _this.renderOutline = false;
  19345. /** Defines color to use when rendering outline */
  19346. _this.outlineColor = BABYLON.Color3.Red();
  19347. /** Define width to use when rendering outline */
  19348. _this.outlineWidth = 0.02;
  19349. /**
  19350. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19351. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19352. */
  19353. _this.renderOverlay = false;
  19354. /** Defines color to use when rendering overlay */
  19355. _this.overlayColor = BABYLON.Color3.Red();
  19356. /** Defines alpha to use when rendering overlay */
  19357. _this.overlayAlpha = 0.5;
  19358. _this._hasVertexAlpha = false;
  19359. _this._useVertexColors = true;
  19360. _this._computeBonesUsingShaders = true;
  19361. _this._numBoneInfluencers = 4;
  19362. _this._applyFog = true;
  19363. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19364. _this.useOctreeForRenderingSelection = true;
  19365. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19366. _this.useOctreeForPicking = true;
  19367. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19368. _this.useOctreeForCollisions = true;
  19369. _this._layerMask = 0x0FFFFFFF;
  19370. /**
  19371. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19372. */
  19373. _this.alwaysSelectAsActiveMesh = false;
  19374. /**
  19375. * Gets or sets the current action manager
  19376. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19377. */
  19378. _this.actionManager = null;
  19379. /**
  19380. * Gets or sets impostor used for physic simulation
  19381. * @see http://doc.babylonjs.com/features/physics_engine
  19382. */
  19383. _this.physicsImpostor = null;
  19384. // Collisions
  19385. _this._checkCollisions = false;
  19386. _this._collisionMask = -1;
  19387. _this._collisionGroup = -1;
  19388. /**
  19389. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19390. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19391. */
  19392. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19393. /**
  19394. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19395. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19396. */
  19397. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19398. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19399. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19400. // Edges
  19401. /**
  19402. * Defines edge width used when edgesRenderer is enabled
  19403. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19404. */
  19405. _this.edgesWidth = 1;
  19406. /**
  19407. * Defines edge color used when edgesRenderer is enabled
  19408. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19409. */
  19410. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19411. // Cache
  19412. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19413. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19414. /** @hidden */
  19415. _this._renderId = 0;
  19416. /** @hidden */
  19417. _this._intersectionsInProgress = new Array();
  19418. /** @hidden */
  19419. _this._unIndexed = false;
  19420. /** @hidden */
  19421. _this._lightSources = new Array();
  19422. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19423. if (collidedMesh === void 0) { collidedMesh = null; }
  19424. //TODO move this to the collision coordinator!
  19425. if (_this.getScene().workerCollisions)
  19426. newPosition.multiplyInPlace(_this._collider._radius);
  19427. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19428. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19429. _this.position.addInPlace(_this._diffPositionForCollisions);
  19430. }
  19431. if (collidedMesh) {
  19432. _this.onCollideObservable.notifyObservers(collidedMesh);
  19433. }
  19434. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19435. };
  19436. _this.getScene().addMesh(_this);
  19437. _this._resyncLightSources();
  19438. return _this;
  19439. }
  19440. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19441. /**
  19442. * No billboard
  19443. */
  19444. get: function () {
  19445. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19446. },
  19447. enumerable: true,
  19448. configurable: true
  19449. });
  19450. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19451. /** Billboard on X axis */
  19452. get: function () {
  19453. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19459. /** Billboard on Y axis */
  19460. get: function () {
  19461. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19467. /** Billboard on Z axis */
  19468. get: function () {
  19469. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19470. },
  19471. enumerable: true,
  19472. configurable: true
  19473. });
  19474. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19475. /** Billboard on all axes */
  19476. get: function () {
  19477. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19478. },
  19479. enumerable: true,
  19480. configurable: true
  19481. });
  19482. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19483. /**
  19484. * Gets the number of facets in the mesh
  19485. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19486. */
  19487. get: function () {
  19488. return this._facetNb;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19494. /**
  19495. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19496. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19497. */
  19498. get: function () {
  19499. return this._partitioningSubdivisions;
  19500. },
  19501. set: function (nb) {
  19502. this._partitioningSubdivisions = nb;
  19503. },
  19504. enumerable: true,
  19505. configurable: true
  19506. });
  19507. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19508. /**
  19509. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19510. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19511. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19512. */
  19513. get: function () {
  19514. return this._partitioningBBoxRatio;
  19515. },
  19516. set: function (ratio) {
  19517. this._partitioningBBoxRatio = ratio;
  19518. },
  19519. enumerable: true,
  19520. configurable: true
  19521. });
  19522. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19523. /**
  19524. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19525. * Works only for updatable meshes.
  19526. * Doesn't work with multi-materials
  19527. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19528. */
  19529. get: function () {
  19530. return this._facetDepthSort;
  19531. },
  19532. set: function (sort) {
  19533. this._facetDepthSort = sort;
  19534. },
  19535. enumerable: true,
  19536. configurable: true
  19537. });
  19538. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19539. /**
  19540. * The location (Vector3) where the facet depth sort must be computed from.
  19541. * By default, the active camera position.
  19542. * Used only when facet depth sort is enabled
  19543. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19544. */
  19545. get: function () {
  19546. return this._facetDepthSortFrom;
  19547. },
  19548. set: function (location) {
  19549. this._facetDepthSortFrom = location;
  19550. },
  19551. enumerable: true,
  19552. configurable: true
  19553. });
  19554. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19555. /**
  19556. * gets a boolean indicating if facetData is enabled
  19557. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19558. */
  19559. get: function () {
  19560. return this._facetDataEnabled;
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. /** @hidden */
  19566. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19567. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19568. return false;
  19569. }
  19570. this._markSubMeshesAsMiscDirty();
  19571. return true;
  19572. };
  19573. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19574. /** Set a function to call when this mesh collides with another one */
  19575. set: function (callback) {
  19576. if (this._onCollideObserver) {
  19577. this.onCollideObservable.remove(this._onCollideObserver);
  19578. }
  19579. this._onCollideObserver = this.onCollideObservable.add(callback);
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19585. /** Set a function to call when the collision's position changes */
  19586. set: function (callback) {
  19587. if (this._onCollisionPositionChangeObserver) {
  19588. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19589. }
  19590. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19591. },
  19592. enumerable: true,
  19593. configurable: true
  19594. });
  19595. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19596. /**
  19597. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19598. * @see http://doc.babylonjs.com/features/occlusionquery
  19599. */
  19600. get: function () {
  19601. return this._isOccluded;
  19602. },
  19603. set: function (value) {
  19604. this._isOccluded = value;
  19605. },
  19606. enumerable: true,
  19607. configurable: true
  19608. });
  19609. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19610. /**
  19611. * Flag to check the progress status of the query
  19612. * @see http://doc.babylonjs.com/features/occlusionquery
  19613. */
  19614. get: function () {
  19615. return this._isOcclusionQueryInProgress;
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19621. /**
  19622. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19623. */
  19624. get: function () {
  19625. return this._visibility;
  19626. },
  19627. /**
  19628. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19629. */
  19630. set: function (value) {
  19631. if (this._visibility === value) {
  19632. return;
  19633. }
  19634. this._visibility = value;
  19635. this._markSubMeshesAsMiscDirty();
  19636. },
  19637. enumerable: true,
  19638. configurable: true
  19639. });
  19640. Object.defineProperty(AbstractMesh.prototype, "material", {
  19641. /** Gets or sets current material */
  19642. get: function () {
  19643. return this._material;
  19644. },
  19645. set: function (value) {
  19646. if (this._material === value) {
  19647. return;
  19648. }
  19649. this._material = value;
  19650. if (this.onMaterialChangedObservable.hasObservers) {
  19651. this.onMaterialChangedObservable.notifyObservers(this);
  19652. }
  19653. if (!this.subMeshes) {
  19654. return;
  19655. }
  19656. this._unBindEffect();
  19657. },
  19658. enumerable: true,
  19659. configurable: true
  19660. });
  19661. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19662. /**
  19663. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19664. * @see http://doc.babylonjs.com/babylon101/shadows
  19665. */
  19666. get: function () {
  19667. return this._receiveShadows;
  19668. },
  19669. set: function (value) {
  19670. if (this._receiveShadows === value) {
  19671. return;
  19672. }
  19673. this._receiveShadows = value;
  19674. this._markSubMeshesAsLightDirty();
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19680. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19681. get: function () {
  19682. return this._hasVertexAlpha;
  19683. },
  19684. set: function (value) {
  19685. if (this._hasVertexAlpha === value) {
  19686. return;
  19687. }
  19688. this._hasVertexAlpha = value;
  19689. this._markSubMeshesAsAttributesDirty();
  19690. this._markSubMeshesAsMiscDirty();
  19691. },
  19692. enumerable: true,
  19693. configurable: true
  19694. });
  19695. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19696. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19697. get: function () {
  19698. return this._useVertexColors;
  19699. },
  19700. set: function (value) {
  19701. if (this._useVertexColors === value) {
  19702. return;
  19703. }
  19704. this._useVertexColors = value;
  19705. this._markSubMeshesAsAttributesDirty();
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19711. /**
  19712. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19713. */
  19714. get: function () {
  19715. return this._computeBonesUsingShaders;
  19716. },
  19717. set: function (value) {
  19718. if (this._computeBonesUsingShaders === value) {
  19719. return;
  19720. }
  19721. this._computeBonesUsingShaders = value;
  19722. this._markSubMeshesAsAttributesDirty();
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19728. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19729. get: function () {
  19730. return this._numBoneInfluencers;
  19731. },
  19732. set: function (value) {
  19733. if (this._numBoneInfluencers === value) {
  19734. return;
  19735. }
  19736. this._numBoneInfluencers = value;
  19737. this._markSubMeshesAsAttributesDirty();
  19738. },
  19739. enumerable: true,
  19740. configurable: true
  19741. });
  19742. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19743. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19744. get: function () {
  19745. return this._applyFog;
  19746. },
  19747. set: function (value) {
  19748. if (this._applyFog === value) {
  19749. return;
  19750. }
  19751. this._applyFog = value;
  19752. this._markSubMeshesAsMiscDirty();
  19753. },
  19754. enumerable: true,
  19755. configurable: true
  19756. });
  19757. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19758. /**
  19759. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19760. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19761. */
  19762. get: function () {
  19763. return this._layerMask;
  19764. },
  19765. set: function (value) {
  19766. if (value === this._layerMask) {
  19767. return;
  19768. }
  19769. this._layerMask = value;
  19770. this._resyncLightSources();
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19776. /**
  19777. * Gets or sets a collision mask used to mask collisions (default is -1).
  19778. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19779. */
  19780. get: function () {
  19781. return this._collisionMask;
  19782. },
  19783. set: function (mask) {
  19784. this._collisionMask = !isNaN(mask) ? mask : -1;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19790. /**
  19791. * Gets or sets the current collision group mask (-1 by default).
  19792. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19793. */
  19794. get: function () {
  19795. return this._collisionGroup;
  19796. },
  19797. set: function (mask) {
  19798. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19804. /** @hidden */
  19805. get: function () {
  19806. return null;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19812. get: function () {
  19813. return this._skeleton;
  19814. },
  19815. /**
  19816. * Gets or sets a skeleton to apply skining transformations
  19817. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19818. */
  19819. set: function (value) {
  19820. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19821. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19822. }
  19823. if (value && value.needInitialSkinMatrix) {
  19824. value._registerMeshWithPoseMatrix(this);
  19825. }
  19826. this._skeleton = value;
  19827. if (!this._skeleton) {
  19828. this._bonesTransformMatrices = null;
  19829. }
  19830. this._markSubMeshesAsAttributesDirty();
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. /**
  19836. * Returns the string "AbstractMesh"
  19837. * @returns "AbstractMesh"
  19838. */
  19839. AbstractMesh.prototype.getClassName = function () {
  19840. return "AbstractMesh";
  19841. };
  19842. /**
  19843. * Gets a string representation of the current mesh
  19844. * @param fullDetails defines a boolean indicating if full details must be included
  19845. * @returns a string representation of the current mesh
  19846. */
  19847. AbstractMesh.prototype.toString = function (fullDetails) {
  19848. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19849. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19850. if (this._skeleton) {
  19851. ret += ", skeleton: " + this._skeleton.name;
  19852. }
  19853. if (fullDetails) {
  19854. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19855. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19856. }
  19857. return ret;
  19858. };
  19859. /** @hidden */
  19860. AbstractMesh.prototype._rebuild = function () {
  19861. if (this._occlusionQuery) {
  19862. this._occlusionQuery = null;
  19863. }
  19864. if (this._edgesRenderer) {
  19865. this._edgesRenderer._rebuild();
  19866. }
  19867. if (!this.subMeshes) {
  19868. return;
  19869. }
  19870. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19871. var subMesh = _a[_i];
  19872. subMesh._rebuild();
  19873. }
  19874. };
  19875. /** @hidden */
  19876. AbstractMesh.prototype._resyncLightSources = function () {
  19877. this._lightSources.length = 0;
  19878. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19879. var light = _a[_i];
  19880. if (!light.isEnabled()) {
  19881. continue;
  19882. }
  19883. if (light.canAffectMesh(this)) {
  19884. this._lightSources.push(light);
  19885. }
  19886. }
  19887. this._markSubMeshesAsLightDirty();
  19888. };
  19889. /** @hidden */
  19890. AbstractMesh.prototype._resyncLighSource = function (light) {
  19891. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19892. var index = this._lightSources.indexOf(light);
  19893. if (index === -1) {
  19894. if (!isIn) {
  19895. return;
  19896. }
  19897. this._lightSources.push(light);
  19898. }
  19899. else {
  19900. if (isIn) {
  19901. return;
  19902. }
  19903. this._lightSources.splice(index, 1);
  19904. }
  19905. this._markSubMeshesAsLightDirty();
  19906. };
  19907. /** @hidden */
  19908. AbstractMesh.prototype._unBindEffect = function () {
  19909. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19910. var subMesh = _a[_i];
  19911. subMesh.setEffect(null);
  19912. }
  19913. };
  19914. /** @hidden */
  19915. AbstractMesh.prototype._removeLightSource = function (light) {
  19916. var index = this._lightSources.indexOf(light);
  19917. if (index === -1) {
  19918. return;
  19919. }
  19920. this._lightSources.splice(index, 1);
  19921. this._markSubMeshesAsLightDirty();
  19922. };
  19923. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19924. if (!this.subMeshes) {
  19925. return;
  19926. }
  19927. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19928. var subMesh = _a[_i];
  19929. if (subMesh._materialDefines) {
  19930. func(subMesh._materialDefines);
  19931. }
  19932. }
  19933. };
  19934. /** @hidden */
  19935. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19936. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19937. };
  19938. /** @hidden */
  19939. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19940. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19941. };
  19942. /** @hidden */
  19943. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19944. if (!this.subMeshes) {
  19945. return;
  19946. }
  19947. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19948. var subMesh = _a[_i];
  19949. var material = subMesh.getMaterial();
  19950. if (material) {
  19951. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19952. }
  19953. }
  19954. };
  19955. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19956. /**
  19957. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19958. */
  19959. get: function () {
  19960. return this._scaling;
  19961. },
  19962. set: function (newScaling) {
  19963. this._scaling = newScaling;
  19964. if (this.physicsImpostor) {
  19965. this.physicsImpostor.forceUpdate();
  19966. }
  19967. },
  19968. enumerable: true,
  19969. configurable: true
  19970. });
  19971. // Methods
  19972. /**
  19973. * Disables the mesh edge rendering mode
  19974. * @returns the currentAbstractMesh
  19975. */
  19976. AbstractMesh.prototype.disableEdgesRendering = function () {
  19977. if (this._edgesRenderer) {
  19978. this._edgesRenderer.dispose();
  19979. this._edgesRenderer = null;
  19980. }
  19981. return this;
  19982. };
  19983. /**
  19984. * Enables the edge rendering mode on the mesh.
  19985. * This mode makes the mesh edges visible
  19986. * @param epsilon defines the maximal distance between two angles to detect a face
  19987. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19988. * @returns the currentAbstractMesh
  19989. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19990. */
  19991. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19992. if (epsilon === void 0) { epsilon = 0.95; }
  19993. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19994. this.disableEdgesRendering();
  19995. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19996. return this;
  19997. };
  19998. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19999. /**
  20000. * Returns true if the mesh is blocked. Implemented by child classes
  20001. */
  20002. get: function () {
  20003. return false;
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. /**
  20009. * Returns the mesh itself by default. Implemented by child classes
  20010. * @param camera defines the camera to use to pick the right LOD level
  20011. * @returns the currentAbstractMesh
  20012. */
  20013. AbstractMesh.prototype.getLOD = function (camera) {
  20014. return this;
  20015. };
  20016. /**
  20017. * Returns 0 by default. Implemented by child classes
  20018. * @returns an integer
  20019. */
  20020. AbstractMesh.prototype.getTotalVertices = function () {
  20021. return 0;
  20022. };
  20023. /**
  20024. * Returns null by default. Implemented by child classes
  20025. * @returns null
  20026. */
  20027. AbstractMesh.prototype.getIndices = function () {
  20028. return null;
  20029. };
  20030. /**
  20031. * Returns the array of the requested vertex data kind. Implemented by child classes
  20032. * @param kind defines the vertex data kind to use
  20033. * @returns null
  20034. */
  20035. AbstractMesh.prototype.getVerticesData = function (kind) {
  20036. return null;
  20037. };
  20038. /**
  20039. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20040. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20041. * Note that a new underlying VertexBuffer object is created each call.
  20042. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20043. * @param kind defines vertex data kind:
  20044. * * BABYLON.VertexBuffer.PositionKind
  20045. * * BABYLON.VertexBuffer.UVKind
  20046. * * BABYLON.VertexBuffer.UV2Kind
  20047. * * BABYLON.VertexBuffer.UV3Kind
  20048. * * BABYLON.VertexBuffer.UV4Kind
  20049. * * BABYLON.VertexBuffer.UV5Kind
  20050. * * BABYLON.VertexBuffer.UV6Kind
  20051. * * BABYLON.VertexBuffer.ColorKind
  20052. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20053. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20054. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20055. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20056. * @param data defines the data source
  20057. * @param updatable defines if the data must be flagged as updatable (or static)
  20058. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20059. * @returns the current mesh
  20060. */
  20061. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20062. return this;
  20063. };
  20064. /**
  20065. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20066. * If the mesh has no geometry, it is simply returned as it is.
  20067. * @param kind defines vertex data kind:
  20068. * * BABYLON.VertexBuffer.PositionKind
  20069. * * BABYLON.VertexBuffer.UVKind
  20070. * * BABYLON.VertexBuffer.UV2Kind
  20071. * * BABYLON.VertexBuffer.UV3Kind
  20072. * * BABYLON.VertexBuffer.UV4Kind
  20073. * * BABYLON.VertexBuffer.UV5Kind
  20074. * * BABYLON.VertexBuffer.UV6Kind
  20075. * * BABYLON.VertexBuffer.ColorKind
  20076. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20077. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20078. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20079. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20080. * @param data defines the data source
  20081. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20082. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20083. * @returns the current mesh
  20084. */
  20085. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20086. return this;
  20087. };
  20088. /**
  20089. * Sets the mesh indices,
  20090. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20091. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20092. * @param totalVertices Defines the total number of vertices
  20093. * @returns the current mesh
  20094. */
  20095. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20096. return this;
  20097. };
  20098. /**
  20099. * Gets a boolean indicating if specific vertex data is present
  20100. * @param kind defines the vertex data kind to use
  20101. * @returns true is data kind is present
  20102. */
  20103. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20104. return false;
  20105. };
  20106. /**
  20107. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20108. * @returns a BoundingInfo
  20109. */
  20110. AbstractMesh.prototype.getBoundingInfo = function () {
  20111. if (this._masterMesh) {
  20112. return this._masterMesh.getBoundingInfo();
  20113. }
  20114. if (!this._boundingInfo) {
  20115. // this._boundingInfo is being created here
  20116. this._updateBoundingInfo();
  20117. }
  20118. // cannot be null.
  20119. return this._boundingInfo;
  20120. };
  20121. /**
  20122. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20123. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20124. * @returns the current mesh
  20125. */
  20126. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20127. if (includeDescendants === void 0) { includeDescendants = true; }
  20128. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20129. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20130. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20131. if (maxDimension === 0) {
  20132. return this;
  20133. }
  20134. var scale = 1 / maxDimension;
  20135. this.scaling.scaleInPlace(scale);
  20136. return this;
  20137. };
  20138. /**
  20139. * Overwrite the current bounding info
  20140. * @param boundingInfo defines the new bounding info
  20141. * @returns the current mesh
  20142. */
  20143. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20144. this._boundingInfo = boundingInfo;
  20145. return this;
  20146. };
  20147. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20148. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20149. get: function () {
  20150. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. /** @hidden */
  20156. AbstractMesh.prototype._preActivate = function () {
  20157. };
  20158. /** @hidden */
  20159. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20160. };
  20161. /** @hidden */
  20162. AbstractMesh.prototype._activate = function (renderId) {
  20163. this._renderId = renderId;
  20164. };
  20165. /**
  20166. * Gets the current world matrix
  20167. * @returns a Matrix
  20168. */
  20169. AbstractMesh.prototype.getWorldMatrix = function () {
  20170. if (this._masterMesh) {
  20171. return this._masterMesh.getWorldMatrix();
  20172. }
  20173. return _super.prototype.getWorldMatrix.call(this);
  20174. };
  20175. /** @hidden */
  20176. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20177. if (this._masterMesh) {
  20178. return this._masterMesh._getWorldMatrixDeterminant();
  20179. }
  20180. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20181. };
  20182. // ================================== Point of View Movement =================================
  20183. /**
  20184. * Perform relative position change from the point of view of behind the front of the mesh.
  20185. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20186. * Supports definition of mesh facing forward or backward
  20187. * @param amountRight defines the distance on the right axis
  20188. * @param amountUp defines the distance on the up axis
  20189. * @param amountForward defines the distance on the forward axis
  20190. * @returns the current mesh
  20191. */
  20192. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20193. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20194. return this;
  20195. };
  20196. /**
  20197. * Calculate relative position change from the point of view of behind the front of the mesh.
  20198. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20199. * Supports definition of mesh facing forward or backward
  20200. * @param amountRight defines the distance on the right axis
  20201. * @param amountUp defines the distance on the up axis
  20202. * @param amountForward defines the distance on the forward axis
  20203. * @returns the new displacement vector
  20204. */
  20205. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20206. var rotMatrix = new BABYLON.Matrix();
  20207. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20208. rotQuaternion.toRotationMatrix(rotMatrix);
  20209. var translationDelta = BABYLON.Vector3.Zero();
  20210. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20211. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20212. return translationDelta;
  20213. };
  20214. // ================================== Point of View Rotation =================================
  20215. /**
  20216. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20217. * Supports definition of mesh facing forward or backward
  20218. * @param flipBack defines the flip
  20219. * @param twirlClockwise defines the twirl
  20220. * @param tiltRight defines the tilt
  20221. * @returns the current mesh
  20222. */
  20223. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20224. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20225. return this;
  20226. };
  20227. /**
  20228. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20229. * Supports definition of mesh facing forward or backward.
  20230. * @param flipBack defines the flip
  20231. * @param twirlClockwise defines the twirl
  20232. * @param tiltRight defines the tilt
  20233. * @returns the new rotation vector
  20234. */
  20235. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20236. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20237. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20238. };
  20239. /**
  20240. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20241. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20242. * @returns the new bounding vectors
  20243. */
  20244. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20245. if (includeDescendants === void 0) { includeDescendants = true; }
  20246. // Ensures that all world matrix will be recomputed.
  20247. this.getScene().incrementRenderId();
  20248. this.computeWorldMatrix(true);
  20249. var min;
  20250. var max;
  20251. var boundingInfo = this.getBoundingInfo();
  20252. if (!this.subMeshes) {
  20253. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20254. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20255. }
  20256. else {
  20257. min = boundingInfo.boundingBox.minimumWorld;
  20258. max = boundingInfo.boundingBox.maximumWorld;
  20259. }
  20260. if (includeDescendants) {
  20261. var descendants = this.getDescendants(false);
  20262. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20263. var descendant = descendants_1[_i];
  20264. var childMesh = descendant;
  20265. childMesh.computeWorldMatrix(true);
  20266. //make sure we have the needed params to get mix and max
  20267. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20268. continue;
  20269. }
  20270. var childBoundingInfo = childMesh.getBoundingInfo();
  20271. var boundingBox = childBoundingInfo.boundingBox;
  20272. var minBox = boundingBox.minimumWorld;
  20273. var maxBox = boundingBox.maximumWorld;
  20274. BABYLON.Tools.CheckExtends(minBox, min, max);
  20275. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20276. }
  20277. }
  20278. return {
  20279. min: min,
  20280. max: max
  20281. };
  20282. };
  20283. /** @hidden */
  20284. AbstractMesh.prototype._updateBoundingInfo = function () {
  20285. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20286. this._boundingInfo.update(this.worldMatrixFromCache);
  20287. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20288. return this;
  20289. };
  20290. /** @hidden */
  20291. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20292. if (!this.subMeshes) {
  20293. return this;
  20294. }
  20295. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20296. var subMesh = this.subMeshes[subIndex];
  20297. if (!subMesh.IsGlobal) {
  20298. subMesh.updateBoundingInfo(matrix);
  20299. }
  20300. }
  20301. return this;
  20302. };
  20303. /** @hidden */
  20304. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20305. // Bounding info
  20306. this._updateBoundingInfo();
  20307. };
  20308. /**
  20309. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20310. * A mesh is in the frustum if its bounding box intersects the frustum
  20311. * @param frustumPlanes defines the frustum to test
  20312. * @returns true if the mesh is in the frustum planes
  20313. */
  20314. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20315. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20316. };
  20317. /**
  20318. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20319. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20320. * @param frustumPlanes defines the frustum to test
  20321. * @returns true if the mesh is completely in the frustum planes
  20322. */
  20323. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20324. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20325. ;
  20326. };
  20327. /**
  20328. * True if the mesh intersects another mesh or a SolidParticle object
  20329. * @param mesh defines a target mesh or SolidParticle to test
  20330. * @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)
  20331. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20332. * @returns true if there is an intersection
  20333. */
  20334. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20335. if (precise === void 0) { precise = false; }
  20336. if (!this._boundingInfo || !mesh._boundingInfo) {
  20337. return false;
  20338. }
  20339. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20340. return true;
  20341. }
  20342. if (includeDescendants) {
  20343. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20344. var child = _a[_i];
  20345. if (child.intersectsMesh(mesh, precise, true)) {
  20346. return true;
  20347. }
  20348. }
  20349. }
  20350. return false;
  20351. };
  20352. /**
  20353. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20354. * @param point defines the point to test
  20355. * @returns true if there is an intersection
  20356. */
  20357. AbstractMesh.prototype.intersectsPoint = function (point) {
  20358. if (!this._boundingInfo) {
  20359. return false;
  20360. }
  20361. return this._boundingInfo.intersectsPoint(point);
  20362. };
  20363. /**
  20364. * Gets the current physics impostor
  20365. * @see http://doc.babylonjs.com/features/physics_engine
  20366. * @returns a physics impostor or null
  20367. */
  20368. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20369. return this.physicsImpostor;
  20370. };
  20371. /**
  20372. * Gets the position of the current mesh in camera space
  20373. * @param camera defines the camera to use
  20374. * @returns a position
  20375. */
  20376. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20377. if (camera === void 0) { camera = null; }
  20378. if (!camera) {
  20379. camera = this.getScene().activeCamera;
  20380. }
  20381. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20382. };
  20383. /**
  20384. * Returns the distance from the mesh to the active camera
  20385. * @param camera defines the camera to use
  20386. * @returns the distance
  20387. */
  20388. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20389. if (camera === void 0) { camera = null; }
  20390. if (!camera) {
  20391. camera = this.getScene().activeCamera;
  20392. }
  20393. return this.absolutePosition.subtract(camera.position).length();
  20394. };
  20395. /**
  20396. * Apply a physic impulse to the mesh
  20397. * @param force defines the force to apply
  20398. * @param contactPoint defines where to apply the force
  20399. * @returns the current mesh
  20400. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20401. */
  20402. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20403. if (!this.physicsImpostor) {
  20404. return this;
  20405. }
  20406. this.physicsImpostor.applyImpulse(force, contactPoint);
  20407. return this;
  20408. };
  20409. /**
  20410. * Creates a physic joint between two meshes
  20411. * @param otherMesh defines the other mesh to use
  20412. * @param pivot1 defines the pivot to use on this mesh
  20413. * @param pivot2 defines the pivot to use on the other mesh
  20414. * @param options defines additional options (can be plugin dependent)
  20415. * @returns the current mesh
  20416. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20417. */
  20418. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20419. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20420. return this;
  20421. }
  20422. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20423. mainPivot: pivot1,
  20424. connectedPivot: pivot2,
  20425. nativeParams: options
  20426. });
  20427. return this;
  20428. };
  20429. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20430. // Collisions
  20431. /**
  20432. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20433. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20434. */
  20435. get: function () {
  20436. return this._checkCollisions;
  20437. },
  20438. set: function (collisionEnabled) {
  20439. this._checkCollisions = collisionEnabled;
  20440. if (this.getScene().workerCollisions) {
  20441. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20442. }
  20443. },
  20444. enumerable: true,
  20445. configurable: true
  20446. });
  20447. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20448. /**
  20449. * Gets Collider object used to compute collisions (not physics)
  20450. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20451. */
  20452. get: function () {
  20453. return this._collider;
  20454. },
  20455. enumerable: true,
  20456. configurable: true
  20457. });
  20458. /**
  20459. * Move the mesh using collision engine
  20460. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20461. * @param displacement defines the requested displacement vector
  20462. * @returns the current mesh
  20463. */
  20464. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20465. var globalPosition = this.getAbsolutePosition();
  20466. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20467. if (!this._collider) {
  20468. this._collider = new BABYLON.Collider();
  20469. }
  20470. this._collider._radius = this.ellipsoid;
  20471. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20472. return this;
  20473. };
  20474. // Submeshes octree
  20475. /**
  20476. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20477. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20478. * @param maxCapacity defines the maximum size of each block (64 by default)
  20479. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20480. * @returns the new octree
  20481. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20482. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20483. */
  20484. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20485. if (maxCapacity === void 0) { maxCapacity = 64; }
  20486. if (maxDepth === void 0) { maxDepth = 2; }
  20487. if (!this._submeshesOctree) {
  20488. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20489. }
  20490. this.computeWorldMatrix(true);
  20491. var boundingInfo = this.getBoundingInfo();
  20492. // Update octree
  20493. var bbox = boundingInfo.boundingBox;
  20494. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20495. return this._submeshesOctree;
  20496. };
  20497. // Collisions
  20498. /** @hidden */
  20499. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20500. this._generatePointsArray();
  20501. if (!this._positions) {
  20502. return this;
  20503. }
  20504. // Transformation
  20505. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20506. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20507. subMesh._lastColliderWorldVertices = [];
  20508. subMesh._trianglePlanes = [];
  20509. var start = subMesh.verticesStart;
  20510. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20511. for (var i = start; i < end; i++) {
  20512. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20513. }
  20514. }
  20515. // Collide
  20516. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20517. if (collider.collisionFound) {
  20518. collider.collidedMesh = this;
  20519. }
  20520. return this;
  20521. };
  20522. /** @hidden */
  20523. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20524. var subMeshes;
  20525. var len;
  20526. // Octrees
  20527. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20528. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20529. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20530. len = intersections.length;
  20531. subMeshes = intersections.data;
  20532. }
  20533. else {
  20534. subMeshes = this.subMeshes;
  20535. len = subMeshes.length;
  20536. }
  20537. for (var index = 0; index < len; index++) {
  20538. var subMesh = subMeshes[index];
  20539. // Bounding test
  20540. if (len > 1 && !subMesh._checkCollision(collider))
  20541. continue;
  20542. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20543. }
  20544. return this;
  20545. };
  20546. /** @hidden */
  20547. AbstractMesh.prototype._checkCollision = function (collider) {
  20548. // Bounding box test
  20549. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20550. return this;
  20551. // Transformation matrix
  20552. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20553. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20554. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20555. return this;
  20556. };
  20557. // Picking
  20558. /** @hidden */
  20559. AbstractMesh.prototype._generatePointsArray = function () {
  20560. return false;
  20561. };
  20562. /**
  20563. * Checks if the passed Ray intersects with the mesh
  20564. * @param ray defines the ray to use
  20565. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20566. * @returns the picking info
  20567. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20568. */
  20569. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20570. var pickingInfo = new BABYLON.PickingInfo();
  20571. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20572. return pickingInfo;
  20573. }
  20574. if (!this._generatePointsArray()) {
  20575. return pickingInfo;
  20576. }
  20577. var intersectInfo = null;
  20578. // Octrees
  20579. var subMeshes;
  20580. var len;
  20581. if (this._submeshesOctree && this.useOctreeForPicking) {
  20582. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20583. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20584. len = intersections.length;
  20585. subMeshes = intersections.data;
  20586. }
  20587. else {
  20588. subMeshes = this.subMeshes;
  20589. len = subMeshes.length;
  20590. }
  20591. for (var index = 0; index < len; index++) {
  20592. var subMesh = subMeshes[index];
  20593. // Bounding test
  20594. if (len > 1 && !subMesh.canIntersects(ray))
  20595. continue;
  20596. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20597. if (currentIntersectInfo) {
  20598. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20599. intersectInfo = currentIntersectInfo;
  20600. intersectInfo.subMeshId = index;
  20601. if (fastCheck) {
  20602. break;
  20603. }
  20604. }
  20605. }
  20606. }
  20607. if (intersectInfo) {
  20608. // Get picked point
  20609. var world = this.getWorldMatrix();
  20610. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20611. var direction = ray.direction.clone();
  20612. direction = direction.scale(intersectInfo.distance);
  20613. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20614. var pickedPoint = worldOrigin.add(worldDirection);
  20615. // Return result
  20616. pickingInfo.hit = true;
  20617. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20618. pickingInfo.pickedPoint = pickedPoint;
  20619. pickingInfo.pickedMesh = this;
  20620. pickingInfo.bu = intersectInfo.bu || 0;
  20621. pickingInfo.bv = intersectInfo.bv || 0;
  20622. pickingInfo.faceId = intersectInfo.faceId;
  20623. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20624. return pickingInfo;
  20625. }
  20626. return pickingInfo;
  20627. };
  20628. /**
  20629. * Clones the current mesh
  20630. * @param name defines the mesh name
  20631. * @param newParent defines the new mesh parent
  20632. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20633. * @returns the new mesh
  20634. */
  20635. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20636. return null;
  20637. };
  20638. /**
  20639. * Disposes all the submeshes of the current meshnp
  20640. * @returns the current mesh
  20641. */
  20642. AbstractMesh.prototype.releaseSubMeshes = function () {
  20643. if (this.subMeshes) {
  20644. while (this.subMeshes.length) {
  20645. this.subMeshes[0].dispose();
  20646. }
  20647. }
  20648. else {
  20649. this.subMeshes = new Array();
  20650. }
  20651. return this;
  20652. };
  20653. /**
  20654. * Releases resources associated with this abstract mesh.
  20655. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20656. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20657. */
  20658. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20659. var _this = this;
  20660. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20661. var index;
  20662. // Smart Array Retainers.
  20663. this.getScene().freeActiveMeshes();
  20664. this.getScene().freeRenderingGroups();
  20665. // Action manager
  20666. if (this.actionManager !== undefined && this.actionManager !== null) {
  20667. this.actionManager.dispose();
  20668. this.actionManager = null;
  20669. }
  20670. // Skeleton
  20671. this._skeleton = null;
  20672. // Physics
  20673. if (this.physicsImpostor) {
  20674. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20675. }
  20676. // Intersections in progress
  20677. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20678. var other = this._intersectionsInProgress[index];
  20679. var pos = other._intersectionsInProgress.indexOf(this);
  20680. other._intersectionsInProgress.splice(pos, 1);
  20681. }
  20682. this._intersectionsInProgress = [];
  20683. // Lights
  20684. var lights = this.getScene().lights;
  20685. lights.forEach(function (light) {
  20686. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20687. if (meshIndex !== -1) {
  20688. light.includedOnlyMeshes.splice(meshIndex, 1);
  20689. }
  20690. meshIndex = light.excludedMeshes.indexOf(_this);
  20691. if (meshIndex !== -1) {
  20692. light.excludedMeshes.splice(meshIndex, 1);
  20693. }
  20694. // Shadow generators
  20695. var generator = light.getShadowGenerator();
  20696. if (generator) {
  20697. var shadowMap = generator.getShadowMap();
  20698. if (shadowMap && shadowMap.renderList) {
  20699. meshIndex = shadowMap.renderList.indexOf(_this);
  20700. if (meshIndex !== -1) {
  20701. shadowMap.renderList.splice(meshIndex, 1);
  20702. }
  20703. }
  20704. }
  20705. });
  20706. // Edges
  20707. if (this._edgesRenderer) {
  20708. this._edgesRenderer.dispose();
  20709. this._edgesRenderer = null;
  20710. }
  20711. // SubMeshes
  20712. if (this.getClassName() !== "InstancedMesh") {
  20713. this.releaseSubMeshes();
  20714. }
  20715. // Octree
  20716. var sceneOctree = this.getScene().selectionOctree;
  20717. if (sceneOctree !== undefined && sceneOctree !== null) {
  20718. var index = sceneOctree.dynamicContent.indexOf(this);
  20719. if (index !== -1) {
  20720. sceneOctree.dynamicContent.splice(index, 1);
  20721. }
  20722. }
  20723. // Query
  20724. var engine = this.getScene().getEngine();
  20725. if (this._occlusionQuery) {
  20726. this._isOcclusionQueryInProgress = false;
  20727. engine.deleteQuery(this._occlusionQuery);
  20728. this._occlusionQuery = null;
  20729. }
  20730. // Engine
  20731. engine.wipeCaches();
  20732. // Remove from scene
  20733. this.getScene().removeMesh(this);
  20734. if (disposeMaterialAndTextures) {
  20735. if (this.material) {
  20736. this.material.dispose(false, true);
  20737. }
  20738. }
  20739. if (!doNotRecurse) {
  20740. // Particles
  20741. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20742. if (this.getScene().particleSystems[index].emitter === this) {
  20743. this.getScene().particleSystems[index].dispose();
  20744. index--;
  20745. }
  20746. }
  20747. }
  20748. // facet data
  20749. if (this._facetDataEnabled) {
  20750. this.disableFacetData();
  20751. }
  20752. this.onAfterWorldMatrixUpdateObservable.clear();
  20753. this.onCollideObservable.clear();
  20754. this.onCollisionPositionChangeObservable.clear();
  20755. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20756. };
  20757. /**
  20758. * Adds the passed mesh as a child to the current mesh
  20759. * @param mesh defines the child mesh
  20760. * @returns the current mesh
  20761. */
  20762. AbstractMesh.prototype.addChild = function (mesh) {
  20763. mesh.setParent(this);
  20764. return this;
  20765. };
  20766. /**
  20767. * Removes the passed mesh from the current mesh children list
  20768. * @param mesh defines the child mesh
  20769. * @returns the current mesh
  20770. */
  20771. AbstractMesh.prototype.removeChild = function (mesh) {
  20772. mesh.setParent(null);
  20773. return this;
  20774. };
  20775. // Facet data
  20776. /** @hidden */
  20777. AbstractMesh.prototype._initFacetData = function () {
  20778. if (!this._facetNormals) {
  20779. this._facetNormals = new Array();
  20780. }
  20781. if (!this._facetPositions) {
  20782. this._facetPositions = new Array();
  20783. }
  20784. if (!this._facetPartitioning) {
  20785. this._facetPartitioning = new Array();
  20786. }
  20787. this._facetNb = (this.getIndices().length / 3) | 0;
  20788. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20789. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20790. for (var f = 0; f < this._facetNb; f++) {
  20791. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20792. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20793. }
  20794. this._facetDataEnabled = true;
  20795. return this;
  20796. };
  20797. /**
  20798. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20799. * This method can be called within the render loop.
  20800. * 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
  20801. * @returns the current mesh
  20802. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20803. */
  20804. AbstractMesh.prototype.updateFacetData = function () {
  20805. if (!this._facetDataEnabled) {
  20806. this._initFacetData();
  20807. }
  20808. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20809. var indices = this.getIndices();
  20810. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20811. var bInfo = this.getBoundingInfo();
  20812. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20813. // init arrays, matrix and sort function on first call
  20814. this._facetDepthSortEnabled = true;
  20815. if (indices instanceof Uint16Array) {
  20816. this._depthSortedIndices = new Uint16Array(indices);
  20817. }
  20818. else if (indices instanceof Uint32Array) {
  20819. this._depthSortedIndices = new Uint32Array(indices);
  20820. }
  20821. else {
  20822. var needs32bits = false;
  20823. for (var i = 0; i < indices.length; i++) {
  20824. if (indices[i] > 65535) {
  20825. needs32bits = true;
  20826. break;
  20827. }
  20828. }
  20829. if (needs32bits) {
  20830. this._depthSortedIndices = new Uint32Array(indices);
  20831. }
  20832. else {
  20833. this._depthSortedIndices = new Uint16Array(indices);
  20834. }
  20835. }
  20836. this._facetDepthSortFunction = function (f1, f2) {
  20837. return (f2.sqDistance - f1.sqDistance);
  20838. };
  20839. if (!this._facetDepthSortFrom) {
  20840. var camera = this.getScene().activeCamera;
  20841. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20842. }
  20843. this._depthSortedFacets = [];
  20844. for (var f = 0; f < this._facetNb; f++) {
  20845. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20846. this._depthSortedFacets.push(depthSortedFacet);
  20847. }
  20848. this._invertedMatrix = BABYLON.Matrix.Identity();
  20849. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20850. }
  20851. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20852. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20853. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20854. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20855. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20856. this._subDiv.max = this._partitioningSubdivisions;
  20857. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20858. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20859. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20860. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20861. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20862. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20863. // set the parameters for ComputeNormals()
  20864. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20865. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20866. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20867. this._facetParameters.bInfo = bInfo;
  20868. this._facetParameters.bbSize = this._bbSize;
  20869. this._facetParameters.subDiv = this._subDiv;
  20870. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20871. this._facetParameters.depthSort = this._facetDepthSort;
  20872. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20873. this.computeWorldMatrix(true);
  20874. this._worldMatrix.invertToRef(this._invertedMatrix);
  20875. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20876. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20877. }
  20878. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20879. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20880. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20881. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20882. var l = (this._depthSortedIndices.length / 3) | 0;
  20883. for (var f = 0; f < l; f++) {
  20884. var sind = this._depthSortedFacets[f].ind;
  20885. this._depthSortedIndices[f * 3] = indices[sind];
  20886. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20887. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20888. }
  20889. this.updateIndices(this._depthSortedIndices);
  20890. }
  20891. return this;
  20892. };
  20893. /**
  20894. * Returns the facetLocalNormals array.
  20895. * The normals are expressed in the mesh local spac
  20896. * @returns an array of Vector3
  20897. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20898. */
  20899. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20900. if (!this._facetNormals) {
  20901. this.updateFacetData();
  20902. }
  20903. return this._facetNormals;
  20904. };
  20905. /**
  20906. * Returns the facetLocalPositions array.
  20907. * The facet positions are expressed in the mesh local space
  20908. * @returns an array of Vector3
  20909. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20910. */
  20911. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20912. if (!this._facetPositions) {
  20913. this.updateFacetData();
  20914. }
  20915. return this._facetPositions;
  20916. };
  20917. /**
  20918. * Returns the facetLocalPartioning array
  20919. * @returns an array of array of numbers
  20920. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20921. */
  20922. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20923. if (!this._facetPartitioning) {
  20924. this.updateFacetData();
  20925. }
  20926. return this._facetPartitioning;
  20927. };
  20928. /**
  20929. * Returns the i-th facet position in the world system.
  20930. * This method allocates a new Vector3 per call
  20931. * @param i defines the facet index
  20932. * @returns a new Vector3
  20933. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20934. */
  20935. AbstractMesh.prototype.getFacetPosition = function (i) {
  20936. var pos = BABYLON.Vector3.Zero();
  20937. this.getFacetPositionToRef(i, pos);
  20938. return pos;
  20939. };
  20940. /**
  20941. * Sets the reference Vector3 with the i-th facet position in the world system
  20942. * @param i defines the facet index
  20943. * @param ref defines the target vector
  20944. * @returns the current mesh
  20945. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20946. */
  20947. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20948. var localPos = (this.getFacetLocalPositions())[i];
  20949. var world = this.getWorldMatrix();
  20950. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20951. return this;
  20952. };
  20953. /**
  20954. * Returns the i-th facet normal in the world system.
  20955. * This method allocates a new Vector3 per call
  20956. * @param i defines the facet index
  20957. * @returns a new Vector3
  20958. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20959. */
  20960. AbstractMesh.prototype.getFacetNormal = function (i) {
  20961. var norm = BABYLON.Vector3.Zero();
  20962. this.getFacetNormalToRef(i, norm);
  20963. return norm;
  20964. };
  20965. /**
  20966. * Sets the reference Vector3 with the i-th facet normal in the world system
  20967. * @param i defines the facet index
  20968. * @param ref defines the target vector
  20969. * @returns the current mesh
  20970. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20971. */
  20972. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20973. var localNorm = (this.getFacetLocalNormals())[i];
  20974. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20975. return this;
  20976. };
  20977. /**
  20978. * 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)
  20979. * @param x defines x coordinate
  20980. * @param y defines y coordinate
  20981. * @param z defines z coordinate
  20982. * @returns the array of facet indexes
  20983. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20984. */
  20985. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20986. var bInfo = this.getBoundingInfo();
  20987. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20988. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20989. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20990. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20991. return null;
  20992. }
  20993. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20994. };
  20995. /**
  20996. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20997. * @param projected sets as the (x,y,z) world projection on the facet
  20998. * @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
  20999. * @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
  21000. * @param x defines x coordinate
  21001. * @param y defines y coordinate
  21002. * @param z defines z coordinate
  21003. * @returns the face index if found (or null instead)
  21004. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21005. */
  21006. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21007. if (checkFace === void 0) { checkFace = false; }
  21008. if (facing === void 0) { facing = true; }
  21009. var world = this.getWorldMatrix();
  21010. var invMat = BABYLON.Tmp.Matrix[5];
  21011. world.invertToRef(invMat);
  21012. var invVect = BABYLON.Tmp.Vector3[8];
  21013. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21014. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21015. if (projected) {
  21016. // tranform the local computed projected vector to world coordinates
  21017. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21018. }
  21019. return closest;
  21020. };
  21021. /**
  21022. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21023. * @param projected sets as the (x,y,z) local projection on the facet
  21024. * @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
  21025. * @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
  21026. * @param x defines x coordinate
  21027. * @param y defines y coordinate
  21028. * @param z defines z coordinate
  21029. * @returns the face index if found (or null instead)
  21030. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21031. */
  21032. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21033. if (checkFace === void 0) { checkFace = false; }
  21034. if (facing === void 0) { facing = true; }
  21035. var closest = null;
  21036. var tmpx = 0.0;
  21037. var tmpy = 0.0;
  21038. var tmpz = 0.0;
  21039. var d = 0.0; // tmp dot facet normal * facet position
  21040. var t0 = 0.0;
  21041. var projx = 0.0;
  21042. var projy = 0.0;
  21043. var projz = 0.0;
  21044. // Get all the facets in the same partitioning block than (x, y, z)
  21045. var facetPositions = this.getFacetLocalPositions();
  21046. var facetNormals = this.getFacetLocalNormals();
  21047. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21048. if (!facetsInBlock) {
  21049. return null;
  21050. }
  21051. // Get the closest facet to (x, y, z)
  21052. var shortest = Number.MAX_VALUE; // init distance vars
  21053. var tmpDistance = shortest;
  21054. var fib; // current facet in the block
  21055. var norm; // current facet normal
  21056. var p0; // current facet barycenter position
  21057. // loop on all the facets in the current partitioning block
  21058. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21059. fib = facetsInBlock[idx];
  21060. norm = facetNormals[fib];
  21061. p0 = facetPositions[fib];
  21062. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21063. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21064. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21065. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21066. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21067. projx = x + norm.x * t0;
  21068. projy = y + norm.y * t0;
  21069. projz = z + norm.z * t0;
  21070. tmpx = projx - x;
  21071. tmpy = projy - y;
  21072. tmpz = projz - z;
  21073. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21074. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21075. shortest = tmpDistance;
  21076. closest = fib;
  21077. if (projected) {
  21078. projected.x = projx;
  21079. projected.y = projy;
  21080. projected.z = projz;
  21081. }
  21082. }
  21083. }
  21084. }
  21085. return closest;
  21086. };
  21087. /**
  21088. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21089. * @returns the parameters
  21090. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21091. */
  21092. AbstractMesh.prototype.getFacetDataParameters = function () {
  21093. return this._facetParameters;
  21094. };
  21095. /**
  21096. * Disables the feature FacetData and frees the related memory
  21097. * @returns the current mesh
  21098. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21099. */
  21100. AbstractMesh.prototype.disableFacetData = function () {
  21101. if (this._facetDataEnabled) {
  21102. this._facetDataEnabled = false;
  21103. this._facetPositions = new Array();
  21104. this._facetNormals = new Array();
  21105. this._facetPartitioning = new Array();
  21106. this._facetParameters = null;
  21107. this._depthSortedIndices = new Uint32Array(0);
  21108. }
  21109. return this;
  21110. };
  21111. /**
  21112. * Updates the AbstractMesh indices array
  21113. * @param indices defines the data source
  21114. * @returns the current mesh
  21115. */
  21116. AbstractMesh.prototype.updateIndices = function (indices) {
  21117. return this;
  21118. };
  21119. /**
  21120. * Creates new normals data for the mesh
  21121. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21122. * @returns the current mesh
  21123. */
  21124. AbstractMesh.prototype.createNormals = function (updatable) {
  21125. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21126. var indices = this.getIndices();
  21127. var normals;
  21128. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21129. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21130. }
  21131. else {
  21132. normals = [];
  21133. }
  21134. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21135. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21136. return this;
  21137. };
  21138. /**
  21139. * Align the mesh with a normal
  21140. * @param normal defines the normal to use
  21141. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21142. * @returns the current mesh
  21143. */
  21144. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21145. if (!upDirection) {
  21146. upDirection = BABYLON.Axis.Y;
  21147. }
  21148. var axisX = BABYLON.Tmp.Vector3[0];
  21149. var axisZ = BABYLON.Tmp.Vector3[1];
  21150. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21151. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21152. if (this.rotationQuaternion) {
  21153. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21154. }
  21155. else {
  21156. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21157. }
  21158. return this;
  21159. };
  21160. /** @hidden */
  21161. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21162. var engine = this.getEngine();
  21163. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21164. this._isOccluded = false;
  21165. return;
  21166. }
  21167. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21168. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21169. if (isOcclusionQueryAvailable) {
  21170. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21171. this._isOcclusionQueryInProgress = false;
  21172. this._occlusionInternalRetryCounter = 0;
  21173. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21174. }
  21175. else {
  21176. this._occlusionInternalRetryCounter++;
  21177. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21178. this._isOcclusionQueryInProgress = false;
  21179. this._occlusionInternalRetryCounter = 0;
  21180. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21181. // if strict continue the last state of the object.
  21182. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21183. }
  21184. else {
  21185. return;
  21186. }
  21187. }
  21188. }
  21189. var scene = this.getScene();
  21190. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21191. if (!this._occlusionQuery) {
  21192. this._occlusionQuery = engine.createQuery();
  21193. }
  21194. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21195. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21196. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21197. this._isOcclusionQueryInProgress = true;
  21198. };
  21199. /** No occlusion */
  21200. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21201. /** Occlusion set to optimisitic */
  21202. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21203. /** Occlusion set to strict */
  21204. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21205. /** Use an accurante occlusion algorithm */
  21206. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21207. /** Use a conservative occlusion algorithm */
  21208. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21209. return AbstractMesh;
  21210. }(BABYLON.TransformNode));
  21211. BABYLON.AbstractMesh = AbstractMesh;
  21212. })(BABYLON || (BABYLON = {}));
  21213. //# sourceMappingURL=babylon.abstractMesh.js.map
  21214. var BABYLON;
  21215. (function (BABYLON) {
  21216. /**
  21217. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21218. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21219. * 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.
  21220. */
  21221. var Light = /** @class */ (function (_super) {
  21222. __extends(Light, _super);
  21223. /**
  21224. * Creates a Light object in the scene.
  21225. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21226. * @param name The firendly name of the light
  21227. * @param scene The scene the light belongs too
  21228. */
  21229. function Light(name, scene) {
  21230. var _this = _super.call(this, name, scene) || this;
  21231. /**
  21232. * Diffuse gives the basic color to an object.
  21233. */
  21234. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21235. /**
  21236. * Specular produces a highlight color on an object.
  21237. * Note: This is note affecting PBR materials.
  21238. */
  21239. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21240. /**
  21241. * Strength of the light.
  21242. * Note: By default it is define in the framework own unit.
  21243. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21244. */
  21245. _this.intensity = 1.0;
  21246. /**
  21247. * Defines how far from the source the light is impacting in scene units.
  21248. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21249. */
  21250. _this.range = Number.MAX_VALUE;
  21251. /**
  21252. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21253. * of light.
  21254. */
  21255. _this._photometricScale = 1.0;
  21256. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21257. _this._radius = 0.00001;
  21258. /**
  21259. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21260. * exceeding the number allowed of the materials.
  21261. */
  21262. _this.renderPriority = 0;
  21263. /**
  21264. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21265. * the current shadow generator.
  21266. */
  21267. _this.shadowEnabled = true;
  21268. _this._excludeWithLayerMask = 0;
  21269. _this._includeOnlyWithLayerMask = 0;
  21270. _this._lightmapMode = 0;
  21271. /**
  21272. * @hidden Internal use only.
  21273. */
  21274. _this._excludedMeshesIds = new Array();
  21275. /**
  21276. * @hidden Internal use only.
  21277. */
  21278. _this._includedOnlyMeshesIds = new Array();
  21279. _this.getScene().addLight(_this);
  21280. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21281. _this._buildUniformLayout();
  21282. _this.includedOnlyMeshes = new Array();
  21283. _this.excludedMeshes = new Array();
  21284. _this._resyncMeshes();
  21285. return _this;
  21286. }
  21287. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21288. /**
  21289. * If every light affecting the material is in this lightmapMode,
  21290. * material.lightmapTexture adds or multiplies
  21291. * (depends on material.useLightmapAsShadowmap)
  21292. * after every other light calculations.
  21293. */
  21294. get: function () {
  21295. return Light._LIGHTMAP_DEFAULT;
  21296. },
  21297. enumerable: true,
  21298. configurable: true
  21299. });
  21300. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21301. /**
  21302. * material.lightmapTexture as only diffuse lighting from this light
  21303. * adds only specular lighting from this light
  21304. * adds dynamic shadows
  21305. */
  21306. get: function () {
  21307. return Light._LIGHTMAP_SPECULAR;
  21308. },
  21309. enumerable: true,
  21310. configurable: true
  21311. });
  21312. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21313. /**
  21314. * material.lightmapTexture as only lighting
  21315. * no light calculation from this light
  21316. * only adds dynamic shadows from this light
  21317. */
  21318. get: function () {
  21319. return Light._LIGHTMAP_SHADOWSONLY;
  21320. },
  21321. enumerable: true,
  21322. configurable: true
  21323. });
  21324. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21325. /**
  21326. * Each light type uses the default quantity according to its type:
  21327. * point/spot lights use luminous intensity
  21328. * directional lights use illuminance
  21329. */
  21330. get: function () {
  21331. return Light._INTENSITYMODE_AUTOMATIC;
  21332. },
  21333. enumerable: true,
  21334. configurable: true
  21335. });
  21336. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21337. /**
  21338. * lumen (lm)
  21339. */
  21340. get: function () {
  21341. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21342. },
  21343. enumerable: true,
  21344. configurable: true
  21345. });
  21346. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21347. /**
  21348. * candela (lm/sr)
  21349. */
  21350. get: function () {
  21351. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21352. },
  21353. enumerable: true,
  21354. configurable: true
  21355. });
  21356. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21357. /**
  21358. * lux (lm/m^2)
  21359. */
  21360. get: function () {
  21361. return Light._INTENSITYMODE_ILLUMINANCE;
  21362. },
  21363. enumerable: true,
  21364. configurable: true
  21365. });
  21366. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21367. /**
  21368. * nit (cd/m^2)
  21369. */
  21370. get: function () {
  21371. return Light._INTENSITYMODE_LUMINANCE;
  21372. },
  21373. enumerable: true,
  21374. configurable: true
  21375. });
  21376. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21377. /**
  21378. * Light type const id of the point light.
  21379. */
  21380. get: function () {
  21381. return Light._LIGHTTYPEID_POINTLIGHT;
  21382. },
  21383. enumerable: true,
  21384. configurable: true
  21385. });
  21386. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21387. /**
  21388. * Light type const id of the directional light.
  21389. */
  21390. get: function () {
  21391. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21392. },
  21393. enumerable: true,
  21394. configurable: true
  21395. });
  21396. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21397. /**
  21398. * Light type const id of the spot light.
  21399. */
  21400. get: function () {
  21401. return Light._LIGHTTYPEID_SPOTLIGHT;
  21402. },
  21403. enumerable: true,
  21404. configurable: true
  21405. });
  21406. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21407. /**
  21408. * Light type const id of the hemispheric light.
  21409. */
  21410. get: function () {
  21411. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21412. },
  21413. enumerable: true,
  21414. configurable: true
  21415. });
  21416. Object.defineProperty(Light.prototype, "intensityMode", {
  21417. /**
  21418. * Gets the photometric scale used to interpret the intensity.
  21419. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21420. */
  21421. get: function () {
  21422. return this._intensityMode;
  21423. },
  21424. /**
  21425. * Sets the photometric scale used to interpret the intensity.
  21426. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21427. */
  21428. set: function (value) {
  21429. this._intensityMode = value;
  21430. this._computePhotometricScale();
  21431. },
  21432. enumerable: true,
  21433. configurable: true
  21434. });
  21435. ;
  21436. ;
  21437. Object.defineProperty(Light.prototype, "radius", {
  21438. /**
  21439. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21440. */
  21441. get: function () {
  21442. return this._radius;
  21443. },
  21444. /**
  21445. * sets the light radius used by PBR Materials to simulate soft area lights.
  21446. */
  21447. set: function (value) {
  21448. this._radius = value;
  21449. this._computePhotometricScale();
  21450. },
  21451. enumerable: true,
  21452. configurable: true
  21453. });
  21454. ;
  21455. ;
  21456. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21457. /**
  21458. * Gets the only meshes impacted by this light.
  21459. */
  21460. get: function () {
  21461. return this._includedOnlyMeshes;
  21462. },
  21463. /**
  21464. * Sets the only meshes impacted by this light.
  21465. */
  21466. set: function (value) {
  21467. this._includedOnlyMeshes = value;
  21468. this._hookArrayForIncludedOnly(value);
  21469. },
  21470. enumerable: true,
  21471. configurable: true
  21472. });
  21473. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21474. /**
  21475. * Gets the meshes not impacted by this light.
  21476. */
  21477. get: function () {
  21478. return this._excludedMeshes;
  21479. },
  21480. /**
  21481. * Sets the meshes not impacted by this light.
  21482. */
  21483. set: function (value) {
  21484. this._excludedMeshes = value;
  21485. this._hookArrayForExcluded(value);
  21486. },
  21487. enumerable: true,
  21488. configurable: true
  21489. });
  21490. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21491. /**
  21492. * Gets the layer id use to find what meshes are not impacted by the light.
  21493. * Inactive if 0
  21494. */
  21495. get: function () {
  21496. return this._excludeWithLayerMask;
  21497. },
  21498. /**
  21499. * Sets the layer id use to find what meshes are not impacted by the light.
  21500. * Inactive if 0
  21501. */
  21502. set: function (value) {
  21503. this._excludeWithLayerMask = value;
  21504. this._resyncMeshes();
  21505. },
  21506. enumerable: true,
  21507. configurable: true
  21508. });
  21509. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21510. /**
  21511. * Gets the layer id use to find what meshes are impacted by the light.
  21512. * Inactive if 0
  21513. */
  21514. get: function () {
  21515. return this._includeOnlyWithLayerMask;
  21516. },
  21517. /**
  21518. * Sets the layer id use to find what meshes are impacted by the light.
  21519. * Inactive if 0
  21520. */
  21521. set: function (value) {
  21522. this._includeOnlyWithLayerMask = value;
  21523. this._resyncMeshes();
  21524. },
  21525. enumerable: true,
  21526. configurable: true
  21527. });
  21528. Object.defineProperty(Light.prototype, "lightmapMode", {
  21529. /**
  21530. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21531. */
  21532. get: function () {
  21533. return this._lightmapMode;
  21534. },
  21535. /**
  21536. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21537. */
  21538. set: function (value) {
  21539. if (this._lightmapMode === value) {
  21540. return;
  21541. }
  21542. this._lightmapMode = value;
  21543. this._markMeshesAsLightDirty();
  21544. },
  21545. enumerable: true,
  21546. configurable: true
  21547. });
  21548. /**
  21549. * Returns the string "Light".
  21550. * @returns the class name
  21551. */
  21552. Light.prototype.getClassName = function () {
  21553. return "Light";
  21554. };
  21555. /**
  21556. * Converts the light information to a readable string for debug purpose.
  21557. * @param fullDetails Supports for multiple levels of logging within scene loading
  21558. * @returns the human readable light info
  21559. */
  21560. Light.prototype.toString = function (fullDetails) {
  21561. var ret = "Name: " + this.name;
  21562. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21563. if (this.animations) {
  21564. for (var i = 0; i < this.animations.length; i++) {
  21565. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21566. }
  21567. }
  21568. if (fullDetails) {
  21569. }
  21570. return ret;
  21571. };
  21572. /**
  21573. * Set the enabled state of this node.
  21574. * @param value - the new enabled state
  21575. */
  21576. Light.prototype.setEnabled = function (value) {
  21577. _super.prototype.setEnabled.call(this, value);
  21578. this._resyncMeshes();
  21579. };
  21580. /**
  21581. * Returns the Light associated shadow generator if any.
  21582. * @return the associated shadow generator.
  21583. */
  21584. Light.prototype.getShadowGenerator = function () {
  21585. return this._shadowGenerator;
  21586. };
  21587. /**
  21588. * Returns a Vector3, the absolute light position in the World.
  21589. * @returns the world space position of the light
  21590. */
  21591. Light.prototype.getAbsolutePosition = function () {
  21592. return BABYLON.Vector3.Zero();
  21593. };
  21594. /**
  21595. * Specifies if the light will affect the passed mesh.
  21596. * @param mesh The mesh to test against the light
  21597. * @return true the mesh is affected otherwise, false.
  21598. */
  21599. Light.prototype.canAffectMesh = function (mesh) {
  21600. if (!mesh) {
  21601. return true;
  21602. }
  21603. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21604. return false;
  21605. }
  21606. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21607. return false;
  21608. }
  21609. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21610. return false;
  21611. }
  21612. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21613. return false;
  21614. }
  21615. return true;
  21616. };
  21617. /**
  21618. * Computes and Returns the light World matrix.
  21619. * @returns the world matrix
  21620. */
  21621. Light.prototype.getWorldMatrix = function () {
  21622. this._currentRenderId = this.getScene().getRenderId();
  21623. this._childRenderId = this._currentRenderId;
  21624. var worldMatrix = this._getWorldMatrix();
  21625. if (this.parent && this.parent.getWorldMatrix) {
  21626. if (!this._parentedWorldMatrix) {
  21627. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21628. }
  21629. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21630. this._markSyncedWithParent();
  21631. return this._parentedWorldMatrix;
  21632. }
  21633. return worldMatrix;
  21634. };
  21635. /**
  21636. * Sort function to order lights for rendering.
  21637. * @param a First Light object to compare to second.
  21638. * @param b Second Light object to compare first.
  21639. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21640. */
  21641. Light.CompareLightsPriority = function (a, b) {
  21642. //shadow-casting lights have priority over non-shadow-casting lights
  21643. //the renderPrioirty is a secondary sort criterion
  21644. if (a.shadowEnabled !== b.shadowEnabled) {
  21645. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21646. }
  21647. return b.renderPriority - a.renderPriority;
  21648. };
  21649. /**
  21650. * Releases resources associated with this node.
  21651. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21652. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21653. */
  21654. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21655. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21656. if (this._shadowGenerator) {
  21657. this._shadowGenerator.dispose();
  21658. this._shadowGenerator = null;
  21659. }
  21660. // Animations
  21661. this.getScene().stopAnimation(this);
  21662. // Remove from meshes
  21663. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21664. var mesh = _a[_i];
  21665. mesh._removeLightSource(this);
  21666. }
  21667. this._uniformBuffer.dispose();
  21668. // Remove from scene
  21669. this.getScene().removeLight(this);
  21670. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21671. };
  21672. /**
  21673. * Returns the light type ID (integer).
  21674. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21675. */
  21676. Light.prototype.getTypeID = function () {
  21677. return 0;
  21678. };
  21679. /**
  21680. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21681. * @returns the scaled intensity in intensity mode unit
  21682. */
  21683. Light.prototype.getScaledIntensity = function () {
  21684. return this._photometricScale * this.intensity;
  21685. };
  21686. /**
  21687. * Returns a new Light object, named "name", from the current one.
  21688. * @param name The name of the cloned light
  21689. * @returns the new created light
  21690. */
  21691. Light.prototype.clone = function (name) {
  21692. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21693. if (!constructor) {
  21694. return null;
  21695. }
  21696. return BABYLON.SerializationHelper.Clone(constructor, this);
  21697. };
  21698. /**
  21699. * Serializes the current light into a Serialization object.
  21700. * @returns the serialized object.
  21701. */
  21702. Light.prototype.serialize = function () {
  21703. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21704. // Type
  21705. serializationObject.type = this.getTypeID();
  21706. // Parent
  21707. if (this.parent) {
  21708. serializationObject.parentId = this.parent.id;
  21709. }
  21710. // Inclusion / exclusions
  21711. if (this.excludedMeshes.length > 0) {
  21712. serializationObject.excludedMeshesIds = [];
  21713. this.excludedMeshes.forEach(function (mesh) {
  21714. serializationObject.excludedMeshesIds.push(mesh.id);
  21715. });
  21716. }
  21717. if (this.includedOnlyMeshes.length > 0) {
  21718. serializationObject.includedOnlyMeshesIds = [];
  21719. this.includedOnlyMeshes.forEach(function (mesh) {
  21720. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21721. });
  21722. }
  21723. // Animations
  21724. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21725. serializationObject.ranges = this.serializeAnimationRanges();
  21726. return serializationObject;
  21727. };
  21728. /**
  21729. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21730. * This new light is named "name" and added to the passed scene.
  21731. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21732. * @param name The friendly name of the light
  21733. * @param scene The scene the new light will belong to
  21734. * @returns the constructor function
  21735. */
  21736. Light.GetConstructorFromName = function (type, name, scene) {
  21737. switch (type) {
  21738. case 0:
  21739. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21740. case 1:
  21741. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21742. case 2:
  21743. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21744. case 3:
  21745. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21746. }
  21747. return null;
  21748. };
  21749. /**
  21750. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21751. * @param parsedLight The JSON representation of the light
  21752. * @param scene The scene to create the parsed light in
  21753. * @returns the created light after parsing
  21754. */
  21755. Light.Parse = function (parsedLight, scene) {
  21756. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21757. if (!constructor) {
  21758. return null;
  21759. }
  21760. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21761. // Inclusion / exclusions
  21762. if (parsedLight.excludedMeshesIds) {
  21763. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21764. }
  21765. if (parsedLight.includedOnlyMeshesIds) {
  21766. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21767. }
  21768. // Parent
  21769. if (parsedLight.parentId) {
  21770. light._waitingParentId = parsedLight.parentId;
  21771. }
  21772. // Animations
  21773. if (parsedLight.animations) {
  21774. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21775. var parsedAnimation = parsedLight.animations[animationIndex];
  21776. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21777. }
  21778. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21779. }
  21780. if (parsedLight.autoAnimate) {
  21781. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21782. }
  21783. return light;
  21784. };
  21785. Light.prototype._hookArrayForExcluded = function (array) {
  21786. var _this = this;
  21787. var oldPush = array.push;
  21788. array.push = function () {
  21789. var items = [];
  21790. for (var _i = 0; _i < arguments.length; _i++) {
  21791. items[_i] = arguments[_i];
  21792. }
  21793. var result = oldPush.apply(array, items);
  21794. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21795. var item = items_1[_a];
  21796. item._resyncLighSource(_this);
  21797. }
  21798. return result;
  21799. };
  21800. var oldSplice = array.splice;
  21801. array.splice = function (index, deleteCount) {
  21802. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21803. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21804. var item = deleted_1[_i];
  21805. item._resyncLighSource(_this);
  21806. }
  21807. return deleted;
  21808. };
  21809. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21810. var item = array_1[_i];
  21811. item._resyncLighSource(this);
  21812. }
  21813. };
  21814. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21815. var _this = this;
  21816. var oldPush = array.push;
  21817. array.push = function () {
  21818. var items = [];
  21819. for (var _i = 0; _i < arguments.length; _i++) {
  21820. items[_i] = arguments[_i];
  21821. }
  21822. var result = oldPush.apply(array, items);
  21823. _this._resyncMeshes();
  21824. return result;
  21825. };
  21826. var oldSplice = array.splice;
  21827. array.splice = function (index, deleteCount) {
  21828. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21829. _this._resyncMeshes();
  21830. return deleted;
  21831. };
  21832. this._resyncMeshes();
  21833. };
  21834. Light.prototype._resyncMeshes = function () {
  21835. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21836. var mesh = _a[_i];
  21837. mesh._resyncLighSource(this);
  21838. }
  21839. };
  21840. /**
  21841. * Forces the meshes to update their light related information in their rendering used effects
  21842. * @hidden Internal Use Only
  21843. */
  21844. Light.prototype._markMeshesAsLightDirty = function () {
  21845. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21846. var mesh = _a[_i];
  21847. if (mesh._lightSources.indexOf(this) !== -1) {
  21848. mesh._markSubMeshesAsLightDirty();
  21849. }
  21850. }
  21851. };
  21852. /**
  21853. * Recomputes the cached photometric scale if needed.
  21854. */
  21855. Light.prototype._computePhotometricScale = function () {
  21856. this._photometricScale = this._getPhotometricScale();
  21857. this.getScene().resetCachedMaterial();
  21858. };
  21859. /**
  21860. * Returns the Photometric Scale according to the light type and intensity mode.
  21861. */
  21862. Light.prototype._getPhotometricScale = function () {
  21863. var photometricScale = 0.0;
  21864. var lightTypeID = this.getTypeID();
  21865. //get photometric mode
  21866. var photometricMode = this.intensityMode;
  21867. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21868. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21869. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21870. }
  21871. else {
  21872. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21873. }
  21874. }
  21875. //compute photometric scale
  21876. switch (lightTypeID) {
  21877. case Light.LIGHTTYPEID_POINTLIGHT:
  21878. case Light.LIGHTTYPEID_SPOTLIGHT:
  21879. switch (photometricMode) {
  21880. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21881. photometricScale = 1.0 / (4.0 * Math.PI);
  21882. break;
  21883. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21884. photometricScale = 1.0;
  21885. break;
  21886. case Light.INTENSITYMODE_LUMINANCE:
  21887. photometricScale = this.radius * this.radius;
  21888. break;
  21889. }
  21890. break;
  21891. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21892. switch (photometricMode) {
  21893. case Light.INTENSITYMODE_ILLUMINANCE:
  21894. photometricScale = 1.0;
  21895. break;
  21896. case Light.INTENSITYMODE_LUMINANCE:
  21897. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21898. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21899. var apexAngleRadians = this.radius;
  21900. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21901. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21902. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21903. photometricScale = solidAngle;
  21904. break;
  21905. }
  21906. break;
  21907. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21908. // No fall off in hemisperic light.
  21909. photometricScale = 1.0;
  21910. break;
  21911. }
  21912. return photometricScale;
  21913. };
  21914. /**
  21915. * Reorder the light in the scene according to their defined priority.
  21916. * @hidden Internal Use Only
  21917. */
  21918. Light.prototype._reorderLightsInScene = function () {
  21919. var scene = this.getScene();
  21920. if (this._renderPriority != 0) {
  21921. scene.requireLightSorting = true;
  21922. }
  21923. this.getScene().sortLightsByPriority();
  21924. };
  21925. //lightmapMode Consts
  21926. Light._LIGHTMAP_DEFAULT = 0;
  21927. Light._LIGHTMAP_SPECULAR = 1;
  21928. Light._LIGHTMAP_SHADOWSONLY = 2;
  21929. // Intensity Mode Consts
  21930. Light._INTENSITYMODE_AUTOMATIC = 0;
  21931. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21932. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21933. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21934. Light._INTENSITYMODE_LUMINANCE = 4;
  21935. // Light types ids const.
  21936. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21937. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21938. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21939. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21940. __decorate([
  21941. BABYLON.serializeAsColor3()
  21942. ], Light.prototype, "diffuse", void 0);
  21943. __decorate([
  21944. BABYLON.serializeAsColor3()
  21945. ], Light.prototype, "specular", void 0);
  21946. __decorate([
  21947. BABYLON.serialize()
  21948. ], Light.prototype, "intensity", void 0);
  21949. __decorate([
  21950. BABYLON.serialize()
  21951. ], Light.prototype, "range", void 0);
  21952. __decorate([
  21953. BABYLON.serialize()
  21954. ], Light.prototype, "intensityMode", null);
  21955. __decorate([
  21956. BABYLON.serialize()
  21957. ], Light.prototype, "radius", null);
  21958. __decorate([
  21959. BABYLON.serialize()
  21960. ], Light.prototype, "_renderPriority", void 0);
  21961. __decorate([
  21962. BABYLON.expandToProperty("_reorderLightsInScene")
  21963. ], Light.prototype, "renderPriority", void 0);
  21964. __decorate([
  21965. BABYLON.serialize()
  21966. ], Light.prototype, "shadowEnabled", void 0);
  21967. __decorate([
  21968. BABYLON.serialize("excludeWithLayerMask")
  21969. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21970. __decorate([
  21971. BABYLON.serialize("includeOnlyWithLayerMask")
  21972. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21973. __decorate([
  21974. BABYLON.serialize("lightmapMode")
  21975. ], Light.prototype, "_lightmapMode", void 0);
  21976. return Light;
  21977. }(BABYLON.Node));
  21978. BABYLON.Light = Light;
  21979. })(BABYLON || (BABYLON = {}));
  21980. //# sourceMappingURL=babylon.light.js.map
  21981. var BABYLON;
  21982. (function (BABYLON) {
  21983. var Camera = /** @class */ (function (_super) {
  21984. __extends(Camera, _super);
  21985. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21986. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21987. var _this = _super.call(this, name, scene) || this;
  21988. /**
  21989. * The vector the camera should consider as up.
  21990. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21991. */
  21992. _this.upVector = BABYLON.Vector3.Up();
  21993. _this.orthoLeft = null;
  21994. _this.orthoRight = null;
  21995. _this.orthoBottom = null;
  21996. _this.orthoTop = null;
  21997. /**
  21998. * FOV is set in Radians. (default is 0.8)
  21999. */
  22000. _this.fov = 0.8;
  22001. _this.minZ = 1;
  22002. _this.maxZ = 10000.0;
  22003. _this.inertia = 0.9;
  22004. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22005. _this.isIntermediate = false;
  22006. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22007. /**
  22008. * Restricts the camera to viewing objects with the same layerMask.
  22009. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22010. */
  22011. _this.layerMask = 0x0FFFFFFF;
  22012. /**
  22013. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22014. */
  22015. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22016. // Camera rig members
  22017. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22018. _this._rigCameras = new Array();
  22019. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22020. _this._skipRendering = false;
  22021. _this.customRenderTargets = new Array();
  22022. // Observables
  22023. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22024. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22025. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22026. _this.onRestoreStateObservable = new BABYLON.Observable();
  22027. // Cache
  22028. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22029. _this._projectionMatrix = new BABYLON.Matrix();
  22030. _this._doNotComputeProjectionMatrix = false;
  22031. _this._worldMatrix = BABYLON.Matrix.Identity();
  22032. _this._postProcesses = new Array();
  22033. _this._transformMatrix = BABYLON.Matrix.Zero();
  22034. _this._activeMeshes = new BABYLON.SmartArray(256);
  22035. _this._globalPosition = BABYLON.Vector3.Zero();
  22036. _this._refreshFrustumPlanes = true;
  22037. _this.getScene().addCamera(_this);
  22038. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22039. _this.getScene().activeCamera = _this;
  22040. }
  22041. _this.position = position;
  22042. return _this;
  22043. }
  22044. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22045. get: function () {
  22046. return Camera._PERSPECTIVE_CAMERA;
  22047. },
  22048. enumerable: true,
  22049. configurable: true
  22050. });
  22051. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22052. get: function () {
  22053. return Camera._ORTHOGRAPHIC_CAMERA;
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22059. /**
  22060. * This is the default FOV mode for perspective cameras.
  22061. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22062. *
  22063. */
  22064. get: function () {
  22065. return Camera._FOVMODE_VERTICAL_FIXED;
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22071. /**
  22072. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22073. *
  22074. */
  22075. get: function () {
  22076. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22077. },
  22078. enumerable: true,
  22079. configurable: true
  22080. });
  22081. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22082. get: function () {
  22083. return Camera._RIG_MODE_NONE;
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22089. get: function () {
  22090. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22091. },
  22092. enumerable: true,
  22093. configurable: true
  22094. });
  22095. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22096. get: function () {
  22097. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22098. },
  22099. enumerable: true,
  22100. configurable: true
  22101. });
  22102. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22103. get: function () {
  22104. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22105. },
  22106. enumerable: true,
  22107. configurable: true
  22108. });
  22109. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22110. get: function () {
  22111. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22117. get: function () {
  22118. return Camera._RIG_MODE_VR;
  22119. },
  22120. enumerable: true,
  22121. configurable: true
  22122. });
  22123. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22124. get: function () {
  22125. return Camera._RIG_MODE_WEBVR;
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. /**
  22131. * Store current camera state (fov, position, etc..)
  22132. */
  22133. Camera.prototype.storeState = function () {
  22134. this._stateStored = true;
  22135. this._storedFov = this.fov;
  22136. return this;
  22137. };
  22138. /**
  22139. * Restores the camera state values if it has been stored. You must call storeState() first
  22140. */
  22141. Camera.prototype._restoreStateValues = function () {
  22142. if (!this._stateStored) {
  22143. return false;
  22144. }
  22145. this.fov = this._storedFov;
  22146. return true;
  22147. };
  22148. /**
  22149. * Restored camera state. You must call storeState() first
  22150. */
  22151. Camera.prototype.restoreState = function () {
  22152. if (this._restoreStateValues()) {
  22153. this.onRestoreStateObservable.notifyObservers(this);
  22154. return true;
  22155. }
  22156. return false;
  22157. };
  22158. Camera.prototype.getClassName = function () {
  22159. return "Camera";
  22160. };
  22161. /**
  22162. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22163. */
  22164. Camera.prototype.toString = function (fullDetails) {
  22165. var ret = "Name: " + this.name;
  22166. ret += ", type: " + this.getClassName();
  22167. if (this.animations) {
  22168. for (var i = 0; i < this.animations.length; i++) {
  22169. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22170. }
  22171. }
  22172. if (fullDetails) {
  22173. }
  22174. return ret;
  22175. };
  22176. Object.defineProperty(Camera.prototype, "globalPosition", {
  22177. get: function () {
  22178. return this._globalPosition;
  22179. },
  22180. enumerable: true,
  22181. configurable: true
  22182. });
  22183. Camera.prototype.getActiveMeshes = function () {
  22184. return this._activeMeshes;
  22185. };
  22186. Camera.prototype.isActiveMesh = function (mesh) {
  22187. return (this._activeMeshes.indexOf(mesh) !== -1);
  22188. };
  22189. /**
  22190. * Is this camera ready to be used/rendered
  22191. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22192. * @return true if the camera is ready
  22193. */
  22194. Camera.prototype.isReady = function (completeCheck) {
  22195. if (completeCheck === void 0) { completeCheck = false; }
  22196. if (completeCheck) {
  22197. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22198. var pp = _a[_i];
  22199. if (pp && !pp.isReady()) {
  22200. return false;
  22201. }
  22202. }
  22203. }
  22204. return _super.prototype.isReady.call(this, completeCheck);
  22205. };
  22206. //Cache
  22207. Camera.prototype._initCache = function () {
  22208. _super.prototype._initCache.call(this);
  22209. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22210. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22211. this._cache.mode = undefined;
  22212. this._cache.minZ = undefined;
  22213. this._cache.maxZ = undefined;
  22214. this._cache.fov = undefined;
  22215. this._cache.fovMode = undefined;
  22216. this._cache.aspectRatio = undefined;
  22217. this._cache.orthoLeft = undefined;
  22218. this._cache.orthoRight = undefined;
  22219. this._cache.orthoBottom = undefined;
  22220. this._cache.orthoTop = undefined;
  22221. this._cache.renderWidth = undefined;
  22222. this._cache.renderHeight = undefined;
  22223. };
  22224. Camera.prototype._updateCache = function (ignoreParentClass) {
  22225. if (!ignoreParentClass) {
  22226. _super.prototype._updateCache.call(this);
  22227. }
  22228. this._cache.position.copyFrom(this.position);
  22229. this._cache.upVector.copyFrom(this.upVector);
  22230. };
  22231. // Synchronized
  22232. Camera.prototype._isSynchronized = function () {
  22233. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22234. };
  22235. Camera.prototype._isSynchronizedViewMatrix = function () {
  22236. if (!_super.prototype._isSynchronized.call(this))
  22237. return false;
  22238. return this._cache.position.equals(this.position)
  22239. && this._cache.upVector.equals(this.upVector)
  22240. && this.isSynchronizedWithParent();
  22241. };
  22242. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22243. var check = this._cache.mode === this.mode
  22244. && this._cache.minZ === this.minZ
  22245. && this._cache.maxZ === this.maxZ;
  22246. if (!check) {
  22247. return false;
  22248. }
  22249. var engine = this.getEngine();
  22250. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22251. check = this._cache.fov === this.fov
  22252. && this._cache.fovMode === this.fovMode
  22253. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22254. }
  22255. else {
  22256. check = this._cache.orthoLeft === this.orthoLeft
  22257. && this._cache.orthoRight === this.orthoRight
  22258. && this._cache.orthoBottom === this.orthoBottom
  22259. && this._cache.orthoTop === this.orthoTop
  22260. && this._cache.renderWidth === engine.getRenderWidth()
  22261. && this._cache.renderHeight === engine.getRenderHeight();
  22262. }
  22263. return check;
  22264. };
  22265. // Controls
  22266. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22267. };
  22268. Camera.prototype.detachControl = function (element) {
  22269. };
  22270. Camera.prototype.update = function () {
  22271. this._checkInputs();
  22272. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22273. this._updateRigCameras();
  22274. }
  22275. };
  22276. Camera.prototype._checkInputs = function () {
  22277. this.onAfterCheckInputsObservable.notifyObservers(this);
  22278. };
  22279. Object.defineProperty(Camera.prototype, "rigCameras", {
  22280. get: function () {
  22281. return this._rigCameras;
  22282. },
  22283. enumerable: true,
  22284. configurable: true
  22285. });
  22286. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22287. get: function () {
  22288. return this._rigPostProcess;
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. /**
  22294. * Internal, gets the first post proces.
  22295. * @returns the first post process to be run on this camera.
  22296. */
  22297. Camera.prototype._getFirstPostProcess = function () {
  22298. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22299. if (this._postProcesses[ppIndex] !== null) {
  22300. return this._postProcesses[ppIndex];
  22301. }
  22302. }
  22303. return null;
  22304. };
  22305. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22306. // invalidate framebuffer
  22307. var firstPostProcess = this._getFirstPostProcess();
  22308. if (firstPostProcess) {
  22309. firstPostProcess.markTextureDirty();
  22310. }
  22311. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22312. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22313. var cam = this._rigCameras[i];
  22314. var rigPostProcess = cam._rigPostProcess;
  22315. // for VR rig, there does not have to be a post process
  22316. if (rigPostProcess) {
  22317. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22318. if (isPass) {
  22319. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22320. cam.isIntermediate = this._postProcesses.length === 0;
  22321. }
  22322. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22323. rigPostProcess.markTextureDirty();
  22324. }
  22325. else {
  22326. cam._postProcesses = this._postProcesses.slice(0);
  22327. }
  22328. }
  22329. };
  22330. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22331. if (insertAt === void 0) { insertAt = null; }
  22332. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22333. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22334. return 0;
  22335. }
  22336. if (insertAt == null || insertAt < 0) {
  22337. this._postProcesses.push(postProcess);
  22338. }
  22339. else if (this._postProcesses[insertAt] === null) {
  22340. this._postProcesses[insertAt] = postProcess;
  22341. }
  22342. else {
  22343. this._postProcesses.splice(insertAt, 0, postProcess);
  22344. }
  22345. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22346. return this._postProcesses.indexOf(postProcess);
  22347. };
  22348. Camera.prototype.detachPostProcess = function (postProcess) {
  22349. var idx = this._postProcesses.indexOf(postProcess);
  22350. if (idx !== -1) {
  22351. this._postProcesses[idx] = null;
  22352. }
  22353. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22354. };
  22355. Camera.prototype.getWorldMatrix = function () {
  22356. if (this._isSynchronizedViewMatrix()) {
  22357. return this._worldMatrix;
  22358. }
  22359. // Getting the the view matrix will also compute the world matrix.
  22360. this.getViewMatrix();
  22361. return this._worldMatrix;
  22362. };
  22363. Camera.prototype._getViewMatrix = function () {
  22364. return BABYLON.Matrix.Identity();
  22365. };
  22366. Camera.prototype.getViewMatrix = function (force) {
  22367. if (!force && this._isSynchronizedViewMatrix()) {
  22368. return this._computedViewMatrix;
  22369. }
  22370. this.updateCache();
  22371. this._computedViewMatrix = this._getViewMatrix();
  22372. this._currentRenderId = this.getScene().getRenderId();
  22373. this._childRenderId = this._currentRenderId;
  22374. this._refreshFrustumPlanes = true;
  22375. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22376. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22377. }
  22378. this.onViewMatrixChangedObservable.notifyObservers(this);
  22379. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22380. return this._computedViewMatrix;
  22381. };
  22382. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22383. this._doNotComputeProjectionMatrix = true;
  22384. if (projection !== undefined) {
  22385. this._projectionMatrix = projection;
  22386. }
  22387. };
  22388. ;
  22389. Camera.prototype.unfreezeProjectionMatrix = function () {
  22390. this._doNotComputeProjectionMatrix = false;
  22391. };
  22392. ;
  22393. Camera.prototype.getProjectionMatrix = function (force) {
  22394. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22395. return this._projectionMatrix;
  22396. }
  22397. // Cache
  22398. this._cache.mode = this.mode;
  22399. this._cache.minZ = this.minZ;
  22400. this._cache.maxZ = this.maxZ;
  22401. // Matrix
  22402. this._refreshFrustumPlanes = true;
  22403. var engine = this.getEngine();
  22404. var scene = this.getScene();
  22405. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22406. this._cache.fov = this.fov;
  22407. this._cache.fovMode = this.fovMode;
  22408. this._cache.aspectRatio = engine.getAspectRatio(this);
  22409. if (this.minZ <= 0) {
  22410. this.minZ = 0.1;
  22411. }
  22412. if (scene.useRightHandedSystem) {
  22413. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22414. }
  22415. else {
  22416. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22417. }
  22418. }
  22419. else {
  22420. var halfWidth = engine.getRenderWidth() / 2.0;
  22421. var halfHeight = engine.getRenderHeight() / 2.0;
  22422. if (scene.useRightHandedSystem) {
  22423. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22424. }
  22425. else {
  22426. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22427. }
  22428. this._cache.orthoLeft = this.orthoLeft;
  22429. this._cache.orthoRight = this.orthoRight;
  22430. this._cache.orthoBottom = this.orthoBottom;
  22431. this._cache.orthoTop = this.orthoTop;
  22432. this._cache.renderWidth = engine.getRenderWidth();
  22433. this._cache.renderHeight = engine.getRenderHeight();
  22434. }
  22435. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22436. return this._projectionMatrix;
  22437. };
  22438. Camera.prototype.getTranformationMatrix = function () {
  22439. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22440. return this._transformMatrix;
  22441. };
  22442. Camera.prototype.updateFrustumPlanes = function () {
  22443. if (!this._refreshFrustumPlanes) {
  22444. return;
  22445. }
  22446. this.getTranformationMatrix();
  22447. if (!this._frustumPlanes) {
  22448. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22449. }
  22450. else {
  22451. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22452. }
  22453. this._refreshFrustumPlanes = false;
  22454. };
  22455. Camera.prototype.isInFrustum = function (target) {
  22456. this.updateFrustumPlanes();
  22457. return target.isInFrustum(this._frustumPlanes);
  22458. };
  22459. Camera.prototype.isCompletelyInFrustum = function (target) {
  22460. this.updateFrustumPlanes();
  22461. return target.isCompletelyInFrustum(this._frustumPlanes);
  22462. };
  22463. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22464. if (length === void 0) { length = 100; }
  22465. if (!transform) {
  22466. transform = this.getWorldMatrix();
  22467. }
  22468. if (!origin) {
  22469. origin = this.position;
  22470. }
  22471. var forward = new BABYLON.Vector3(0, 0, 1);
  22472. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22473. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22474. return new BABYLON.Ray(origin, direction, length);
  22475. };
  22476. /**
  22477. * Releases resources associated with this node.
  22478. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22479. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22480. */
  22481. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22482. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22483. // Observables
  22484. this.onViewMatrixChangedObservable.clear();
  22485. this.onProjectionMatrixChangedObservable.clear();
  22486. this.onAfterCheckInputsObservable.clear();
  22487. this.onRestoreStateObservable.clear();
  22488. // Inputs
  22489. if (this.inputs) {
  22490. this.inputs.clear();
  22491. }
  22492. // Animations
  22493. this.getScene().stopAnimation(this);
  22494. // Remove from scene
  22495. this.getScene().removeCamera(this);
  22496. while (this._rigCameras.length > 0) {
  22497. var camera = this._rigCameras.pop();
  22498. if (camera) {
  22499. camera.dispose();
  22500. }
  22501. }
  22502. // Postprocesses
  22503. if (this._rigPostProcess) {
  22504. this._rigPostProcess.dispose(this);
  22505. this._rigPostProcess = null;
  22506. this._postProcesses = [];
  22507. }
  22508. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22509. this._rigPostProcess = null;
  22510. this._postProcesses = [];
  22511. }
  22512. else {
  22513. var i = this._postProcesses.length;
  22514. while (--i >= 0) {
  22515. var postProcess = this._postProcesses[i];
  22516. if (postProcess) {
  22517. postProcess.dispose(this);
  22518. }
  22519. }
  22520. }
  22521. // Render targets
  22522. var i = this.customRenderTargets.length;
  22523. while (--i >= 0) {
  22524. this.customRenderTargets[i].dispose();
  22525. }
  22526. this.customRenderTargets = [];
  22527. // Active Meshes
  22528. this._activeMeshes.dispose();
  22529. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22530. };
  22531. Object.defineProperty(Camera.prototype, "leftCamera", {
  22532. // ---- Camera rigs section ----
  22533. get: function () {
  22534. if (this._rigCameras.length < 1) {
  22535. return null;
  22536. }
  22537. return this._rigCameras[0];
  22538. },
  22539. enumerable: true,
  22540. configurable: true
  22541. });
  22542. Object.defineProperty(Camera.prototype, "rightCamera", {
  22543. get: function () {
  22544. if (this._rigCameras.length < 2) {
  22545. return null;
  22546. }
  22547. return this._rigCameras[1];
  22548. },
  22549. enumerable: true,
  22550. configurable: true
  22551. });
  22552. Camera.prototype.getLeftTarget = function () {
  22553. if (this._rigCameras.length < 1) {
  22554. return null;
  22555. }
  22556. return this._rigCameras[0].getTarget();
  22557. };
  22558. Camera.prototype.getRightTarget = function () {
  22559. if (this._rigCameras.length < 2) {
  22560. return null;
  22561. }
  22562. return this._rigCameras[1].getTarget();
  22563. };
  22564. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22565. if (this.cameraRigMode === mode) {
  22566. return;
  22567. }
  22568. while (this._rigCameras.length > 0) {
  22569. var camera = this._rigCameras.pop();
  22570. if (camera) {
  22571. camera.dispose();
  22572. }
  22573. }
  22574. this.cameraRigMode = mode;
  22575. this._cameraRigParams = {};
  22576. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22577. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22578. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22579. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22580. // create the rig cameras, unless none
  22581. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22582. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22583. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22584. if (leftCamera && rightCamera) {
  22585. this._rigCameras.push(leftCamera);
  22586. this._rigCameras.push(rightCamera);
  22587. }
  22588. }
  22589. switch (this.cameraRigMode) {
  22590. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22591. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22592. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22593. break;
  22594. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22595. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22596. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22597. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22598. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22599. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22600. break;
  22601. case Camera.RIG_MODE_VR:
  22602. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22603. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22604. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22605. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22606. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22607. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22608. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22609. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22610. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22611. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22612. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22613. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22614. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22615. if (metrics.compensateDistortion) {
  22616. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22617. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22618. }
  22619. break;
  22620. case Camera.RIG_MODE_WEBVR:
  22621. if (rigParams.vrDisplay) {
  22622. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22623. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22624. //Left eye
  22625. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22626. this._rigCameras[0].setCameraRigParameter("left", true);
  22627. //leaving this for future reference
  22628. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22629. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22630. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22631. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22632. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22633. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22634. this._rigCameras[0].parent = this;
  22635. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22636. //Right eye
  22637. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22638. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22639. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22640. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22641. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22642. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22643. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22644. this._rigCameras[1].parent = this;
  22645. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22646. if (Camera.UseAlternateWebVRRendering) {
  22647. this._rigCameras[1]._skipRendering = true;
  22648. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22649. }
  22650. }
  22651. break;
  22652. }
  22653. this._cascadePostProcessesToRigCams();
  22654. this.update();
  22655. };
  22656. Camera.prototype._getVRProjectionMatrix = function () {
  22657. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22658. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22659. return this._projectionMatrix;
  22660. };
  22661. Camera.prototype._updateCameraRotationMatrix = function () {
  22662. //Here for WebVR
  22663. };
  22664. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22665. //Here for WebVR
  22666. };
  22667. /**
  22668. * This function MUST be overwritten by the different WebVR cameras available.
  22669. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22670. */
  22671. Camera.prototype._getWebVRProjectionMatrix = function () {
  22672. return BABYLON.Matrix.Identity();
  22673. };
  22674. /**
  22675. * This function MUST be overwritten by the different WebVR cameras available.
  22676. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22677. */
  22678. Camera.prototype._getWebVRViewMatrix = function () {
  22679. return BABYLON.Matrix.Identity();
  22680. };
  22681. Camera.prototype.setCameraRigParameter = function (name, value) {
  22682. if (!this._cameraRigParams) {
  22683. this._cameraRigParams = {};
  22684. }
  22685. this._cameraRigParams[name] = value;
  22686. //provisionnally:
  22687. if (name === "interaxialDistance") {
  22688. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22689. }
  22690. };
  22691. /**
  22692. * needs to be overridden by children so sub has required properties to be copied
  22693. */
  22694. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22695. return null;
  22696. };
  22697. /**
  22698. * May need to be overridden by children
  22699. */
  22700. Camera.prototype._updateRigCameras = function () {
  22701. for (var i = 0; i < this._rigCameras.length; i++) {
  22702. this._rigCameras[i].minZ = this.minZ;
  22703. this._rigCameras[i].maxZ = this.maxZ;
  22704. this._rigCameras[i].fov = this.fov;
  22705. }
  22706. // only update viewport when ANAGLYPH
  22707. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22708. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22709. }
  22710. };
  22711. Camera.prototype._setupInputs = function () {
  22712. };
  22713. Camera.prototype.serialize = function () {
  22714. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22715. // Type
  22716. serializationObject.type = this.getClassName();
  22717. // Parent
  22718. if (this.parent) {
  22719. serializationObject.parentId = this.parent.id;
  22720. }
  22721. if (this.inputs) {
  22722. this.inputs.serialize(serializationObject);
  22723. }
  22724. // Animations
  22725. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22726. serializationObject.ranges = this.serializeAnimationRanges();
  22727. return serializationObject;
  22728. };
  22729. Camera.prototype.clone = function (name) {
  22730. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22731. };
  22732. Camera.prototype.getDirection = function (localAxis) {
  22733. var result = BABYLON.Vector3.Zero();
  22734. this.getDirectionToRef(localAxis, result);
  22735. return result;
  22736. };
  22737. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22738. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22739. };
  22740. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22741. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22742. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22743. switch (type) {
  22744. case "ArcRotateCamera":
  22745. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22746. case "DeviceOrientationCamera":
  22747. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22748. case "FollowCamera":
  22749. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22750. case "ArcFollowCamera":
  22751. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22752. case "GamepadCamera":
  22753. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22754. case "TouchCamera":
  22755. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22756. case "VirtualJoysticksCamera":
  22757. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22758. case "WebVRFreeCamera":
  22759. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22760. case "WebVRGamepadCamera":
  22761. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22762. case "VRDeviceOrientationFreeCamera":
  22763. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22764. case "VRDeviceOrientationGamepadCamera":
  22765. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22766. case "AnaglyphArcRotateCamera":
  22767. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22768. case "AnaglyphFreeCamera":
  22769. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22770. case "AnaglyphGamepadCamera":
  22771. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22772. case "AnaglyphUniversalCamera":
  22773. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22774. case "StereoscopicArcRotateCamera":
  22775. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22776. case "StereoscopicFreeCamera":
  22777. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22778. case "StereoscopicGamepadCamera":
  22779. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22780. case "StereoscopicUniversalCamera":
  22781. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22782. case "FreeCamera": // Forcing Universal here
  22783. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22784. default: // Universal Camera is the default value
  22785. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22786. }
  22787. };
  22788. Camera.prototype.computeWorldMatrix = function () {
  22789. return this.getWorldMatrix();
  22790. };
  22791. Camera.Parse = function (parsedCamera, scene) {
  22792. var type = parsedCamera.type;
  22793. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22794. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22795. // Parent
  22796. if (parsedCamera.parentId) {
  22797. camera._waitingParentId = parsedCamera.parentId;
  22798. }
  22799. //If camera has an input manager, let it parse inputs settings
  22800. if (camera.inputs) {
  22801. camera.inputs.parse(parsedCamera);
  22802. camera._setupInputs();
  22803. }
  22804. if (camera.setPosition) { // need to force position
  22805. camera.position.copyFromFloats(0, 0, 0);
  22806. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22807. }
  22808. // Target
  22809. if (parsedCamera.target) {
  22810. if (camera.setTarget) {
  22811. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22812. }
  22813. }
  22814. // Apply 3d rig, when found
  22815. if (parsedCamera.cameraRigMode) {
  22816. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22817. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22818. }
  22819. // Animations
  22820. if (parsedCamera.animations) {
  22821. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22822. var parsedAnimation = parsedCamera.animations[animationIndex];
  22823. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22824. }
  22825. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22826. }
  22827. if (parsedCamera.autoAnimate) {
  22828. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22829. }
  22830. return camera;
  22831. };
  22832. // Statics
  22833. Camera._PERSPECTIVE_CAMERA = 0;
  22834. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22835. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22836. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22837. Camera._RIG_MODE_NONE = 0;
  22838. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22839. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22840. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22841. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22842. Camera._RIG_MODE_VR = 20;
  22843. Camera._RIG_MODE_WEBVR = 21;
  22844. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22845. Camera.UseAlternateWebVRRendering = false;
  22846. __decorate([
  22847. BABYLON.serializeAsVector3()
  22848. ], Camera.prototype, "position", void 0);
  22849. __decorate([
  22850. BABYLON.serializeAsVector3()
  22851. ], Camera.prototype, "upVector", void 0);
  22852. __decorate([
  22853. BABYLON.serialize()
  22854. ], Camera.prototype, "orthoLeft", void 0);
  22855. __decorate([
  22856. BABYLON.serialize()
  22857. ], Camera.prototype, "orthoRight", void 0);
  22858. __decorate([
  22859. BABYLON.serialize()
  22860. ], Camera.prototype, "orthoBottom", void 0);
  22861. __decorate([
  22862. BABYLON.serialize()
  22863. ], Camera.prototype, "orthoTop", void 0);
  22864. __decorate([
  22865. BABYLON.serialize()
  22866. ], Camera.prototype, "fov", void 0);
  22867. __decorate([
  22868. BABYLON.serialize()
  22869. ], Camera.prototype, "minZ", void 0);
  22870. __decorate([
  22871. BABYLON.serialize()
  22872. ], Camera.prototype, "maxZ", void 0);
  22873. __decorate([
  22874. BABYLON.serialize()
  22875. ], Camera.prototype, "inertia", void 0);
  22876. __decorate([
  22877. BABYLON.serialize()
  22878. ], Camera.prototype, "mode", void 0);
  22879. __decorate([
  22880. BABYLON.serialize()
  22881. ], Camera.prototype, "layerMask", void 0);
  22882. __decorate([
  22883. BABYLON.serialize()
  22884. ], Camera.prototype, "fovMode", void 0);
  22885. __decorate([
  22886. BABYLON.serialize()
  22887. ], Camera.prototype, "cameraRigMode", void 0);
  22888. __decorate([
  22889. BABYLON.serialize()
  22890. ], Camera.prototype, "interaxialDistance", void 0);
  22891. __decorate([
  22892. BABYLON.serialize()
  22893. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22894. return Camera;
  22895. }(BABYLON.Node));
  22896. BABYLON.Camera = Camera;
  22897. })(BABYLON || (BABYLON = {}));
  22898. //# sourceMappingURL=babylon.camera.js.map
  22899. var BABYLON;
  22900. (function (BABYLON) {
  22901. var RenderingManager = /** @class */ (function () {
  22902. function RenderingManager(scene) {
  22903. this._renderingGroups = new Array();
  22904. this._autoClearDepthStencil = {};
  22905. this._customOpaqueSortCompareFn = {};
  22906. this._customAlphaTestSortCompareFn = {};
  22907. this._customTransparentSortCompareFn = {};
  22908. this._renderinGroupInfo = null;
  22909. this._scene = scene;
  22910. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22911. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22912. }
  22913. }
  22914. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22915. if (depth === void 0) { depth = true; }
  22916. if (stencil === void 0) { stencil = true; }
  22917. if (this._depthStencilBufferAlreadyCleaned) {
  22918. return;
  22919. }
  22920. this._scene.getEngine().clear(null, false, depth, stencil);
  22921. this._depthStencilBufferAlreadyCleaned = true;
  22922. };
  22923. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22924. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22925. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22926. var info = null;
  22927. if (observable) {
  22928. if (!this._renderinGroupInfo) {
  22929. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22930. }
  22931. info = this._renderinGroupInfo;
  22932. info.scene = this._scene;
  22933. info.camera = this._scene.activeCamera;
  22934. }
  22935. // Dispatch sprites
  22936. if (renderSprites) {
  22937. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22938. var manager = this._scene.spriteManagers[index];
  22939. this.dispatchSprites(manager);
  22940. }
  22941. }
  22942. // Render
  22943. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22944. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22945. var renderingGroup = this._renderingGroups[index];
  22946. if (!renderingGroup && !observable)
  22947. continue;
  22948. var renderingGroupMask = 0;
  22949. // Fire PRECLEAR stage
  22950. if (observable && info) {
  22951. renderingGroupMask = Math.pow(2, index);
  22952. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22953. info.renderingGroupId = index;
  22954. observable.notifyObservers(info, renderingGroupMask);
  22955. }
  22956. // Clear depth/stencil if needed
  22957. if (RenderingManager.AUTOCLEAR) {
  22958. var autoClear = this._autoClearDepthStencil[index];
  22959. if (autoClear && autoClear.autoClear) {
  22960. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22961. }
  22962. }
  22963. if (observable && info) {
  22964. // Fire PREOPAQUE stage
  22965. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22966. observable.notifyObservers(info, renderingGroupMask);
  22967. // Fire PRETRANSPARENT stage
  22968. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22969. observable.notifyObservers(info, renderingGroupMask);
  22970. }
  22971. if (renderingGroup)
  22972. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22973. // Fire POSTTRANSPARENT stage
  22974. if (observable && info) {
  22975. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22976. observable.notifyObservers(info, renderingGroupMask);
  22977. }
  22978. }
  22979. };
  22980. RenderingManager.prototype.reset = function () {
  22981. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22982. var renderingGroup = this._renderingGroups[index];
  22983. if (renderingGroup) {
  22984. renderingGroup.prepare();
  22985. }
  22986. }
  22987. };
  22988. RenderingManager.prototype.dispose = function () {
  22989. this.freeRenderingGroups();
  22990. this._renderingGroups.length = 0;
  22991. };
  22992. /**
  22993. * Clear the info related to rendering groups preventing retention points during dispose.
  22994. */
  22995. RenderingManager.prototype.freeRenderingGroups = function () {
  22996. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22997. var renderingGroup = this._renderingGroups[index];
  22998. if (renderingGroup) {
  22999. renderingGroup.dispose();
  23000. }
  23001. }
  23002. };
  23003. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23004. if (this._renderingGroups[renderingGroupId] === undefined) {
  23005. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23006. }
  23007. };
  23008. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23009. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23010. this._prepareRenderingGroup(renderingGroupId);
  23011. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23012. };
  23013. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23014. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23015. this._prepareRenderingGroup(renderingGroupId);
  23016. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23017. };
  23018. /**
  23019. * @param subMesh The submesh to dispatch
  23020. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23021. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23022. */
  23023. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23024. if (mesh === undefined) {
  23025. mesh = subMesh.getMesh();
  23026. }
  23027. var renderingGroupId = mesh.renderingGroupId || 0;
  23028. this._prepareRenderingGroup(renderingGroupId);
  23029. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23030. };
  23031. /**
  23032. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23033. * This allowed control for front to back rendering or reversly depending of the special needs.
  23034. *
  23035. * @param renderingGroupId The rendering group id corresponding to its index
  23036. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23037. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23038. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23039. */
  23040. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23041. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23042. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23043. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23044. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23045. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23046. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23047. if (this._renderingGroups[renderingGroupId]) {
  23048. var group = this._renderingGroups[renderingGroupId];
  23049. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23050. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23051. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23052. }
  23053. };
  23054. /**
  23055. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23056. *
  23057. * @param renderingGroupId The rendering group id corresponding to its index
  23058. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23059. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23060. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23061. */
  23062. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23063. if (depth === void 0) { depth = true; }
  23064. if (stencil === void 0) { stencil = true; }
  23065. this._autoClearDepthStencil[renderingGroupId] = {
  23066. autoClear: autoClearDepthStencil,
  23067. depth: depth,
  23068. stencil: stencil
  23069. };
  23070. };
  23071. /**
  23072. * The max id used for rendering groups (not included)
  23073. */
  23074. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23075. /**
  23076. * The min id used for rendering groups (included)
  23077. */
  23078. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23079. /**
  23080. * Used to globally prevent autoclearing scenes.
  23081. */
  23082. RenderingManager.AUTOCLEAR = true;
  23083. return RenderingManager;
  23084. }());
  23085. BABYLON.RenderingManager = RenderingManager;
  23086. })(BABYLON || (BABYLON = {}));
  23087. //# sourceMappingURL=babylon.renderingManager.js.map
  23088. var BABYLON;
  23089. (function (BABYLON) {
  23090. var RenderingGroup = /** @class */ (function () {
  23091. /**
  23092. * Creates a new rendering group.
  23093. * @param index The rendering group index
  23094. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23095. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23096. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23097. */
  23098. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23099. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23100. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23101. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23102. this.index = index;
  23103. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23104. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23105. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23106. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23107. this._particleSystems = new BABYLON.SmartArray(256);
  23108. this._spriteManagers = new BABYLON.SmartArray(256);
  23109. this._edgesRenderers = new BABYLON.SmartArray(16);
  23110. this._scene = scene;
  23111. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23112. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23113. this.transparentSortCompareFn = transparentSortCompareFn;
  23114. }
  23115. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23116. /**
  23117. * Set the opaque sort comparison function.
  23118. * If null the sub meshes will be render in the order they were created
  23119. */
  23120. set: function (value) {
  23121. this._opaqueSortCompareFn = value;
  23122. if (value) {
  23123. this._renderOpaque = this.renderOpaqueSorted;
  23124. }
  23125. else {
  23126. this._renderOpaque = RenderingGroup.renderUnsorted;
  23127. }
  23128. },
  23129. enumerable: true,
  23130. configurable: true
  23131. });
  23132. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23133. /**
  23134. * Set the alpha test sort comparison function.
  23135. * If null the sub meshes will be render in the order they were created
  23136. */
  23137. set: function (value) {
  23138. this._alphaTestSortCompareFn = value;
  23139. if (value) {
  23140. this._renderAlphaTest = this.renderAlphaTestSorted;
  23141. }
  23142. else {
  23143. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23144. }
  23145. },
  23146. enumerable: true,
  23147. configurable: true
  23148. });
  23149. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23150. /**
  23151. * Set the transparent sort comparison function.
  23152. * If null the sub meshes will be render in the order they were created
  23153. */
  23154. set: function (value) {
  23155. if (value) {
  23156. this._transparentSortCompareFn = value;
  23157. }
  23158. else {
  23159. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23160. }
  23161. this._renderTransparent = this.renderTransparentSorted;
  23162. },
  23163. enumerable: true,
  23164. configurable: true
  23165. });
  23166. /**
  23167. * Render all the sub meshes contained in the group.
  23168. * @param customRenderFunction Used to override the default render behaviour of the group.
  23169. * @returns true if rendered some submeshes.
  23170. */
  23171. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23172. if (customRenderFunction) {
  23173. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23174. return;
  23175. }
  23176. var engine = this._scene.getEngine();
  23177. // Depth only
  23178. if (this._depthOnlySubMeshes.length !== 0) {
  23179. engine.setColorWrite(false);
  23180. this._renderAlphaTest(this._depthOnlySubMeshes);
  23181. engine.setColorWrite(true);
  23182. }
  23183. // Opaque
  23184. if (this._opaqueSubMeshes.length !== 0) {
  23185. this._renderOpaque(this._opaqueSubMeshes);
  23186. }
  23187. // Alpha test
  23188. if (this._alphaTestSubMeshes.length !== 0) {
  23189. this._renderAlphaTest(this._alphaTestSubMeshes);
  23190. }
  23191. var stencilState = engine.getStencilBuffer();
  23192. engine.setStencilBuffer(false);
  23193. // Sprites
  23194. if (renderSprites) {
  23195. this._renderSprites();
  23196. }
  23197. // Particles
  23198. if (renderParticles) {
  23199. this._renderParticles(activeMeshes);
  23200. }
  23201. if (this.onBeforeTransparentRendering) {
  23202. this.onBeforeTransparentRendering();
  23203. }
  23204. // Transparent
  23205. if (this._transparentSubMeshes.length !== 0) {
  23206. this._renderTransparent(this._transparentSubMeshes);
  23207. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23208. }
  23209. // Set back stencil to false in case it changes before the edge renderer.
  23210. engine.setStencilBuffer(false);
  23211. // Edges
  23212. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23213. this._edgesRenderers.data[edgesRendererIndex].render();
  23214. }
  23215. // Restore Stencil state.
  23216. engine.setStencilBuffer(stencilState);
  23217. };
  23218. /**
  23219. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23220. * @param subMeshes The submeshes to render
  23221. */
  23222. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23223. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23224. };
  23225. /**
  23226. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23227. * @param subMeshes The submeshes to render
  23228. */
  23229. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23230. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23231. };
  23232. /**
  23233. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23234. * @param subMeshes The submeshes to render
  23235. */
  23236. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23237. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23238. };
  23239. /**
  23240. * Renders the submeshes in a specified order.
  23241. * @param subMeshes The submeshes to sort before render
  23242. * @param sortCompareFn The comparison function use to sort
  23243. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23244. * @param transparent Specifies to activate blending if true
  23245. */
  23246. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23247. var subIndex = 0;
  23248. var subMesh;
  23249. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23250. for (; subIndex < subMeshes.length; subIndex++) {
  23251. subMesh = subMeshes.data[subIndex];
  23252. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23253. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23254. }
  23255. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23256. if (sortCompareFn) {
  23257. sortedArray.sort(sortCompareFn);
  23258. }
  23259. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23260. subMesh = sortedArray[subIndex];
  23261. if (transparent) {
  23262. var material = subMesh.getMaterial();
  23263. if (material && material.needDepthPrePass) {
  23264. var engine = material.getScene().getEngine();
  23265. engine.setColorWrite(false);
  23266. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23267. subMesh.render(false);
  23268. engine.setColorWrite(true);
  23269. }
  23270. }
  23271. subMesh.render(transparent);
  23272. }
  23273. };
  23274. /**
  23275. * Renders the submeshes in the order they were dispatched (no sort applied).
  23276. * @param subMeshes The submeshes to render
  23277. */
  23278. RenderingGroup.renderUnsorted = function (subMeshes) {
  23279. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23280. var submesh = subMeshes.data[subIndex];
  23281. submesh.render(false);
  23282. }
  23283. };
  23284. /**
  23285. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23286. * are rendered back to front if in the same alpha index.
  23287. *
  23288. * @param a The first submesh
  23289. * @param b The second submesh
  23290. * @returns The result of the comparison
  23291. */
  23292. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23293. // Alpha index first
  23294. if (a._alphaIndex > b._alphaIndex) {
  23295. return 1;
  23296. }
  23297. if (a._alphaIndex < b._alphaIndex) {
  23298. return -1;
  23299. }
  23300. // Then distance to camera
  23301. return RenderingGroup.backToFrontSortCompare(a, b);
  23302. };
  23303. /**
  23304. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23305. * are rendered back to front.
  23306. *
  23307. * @param a The first submesh
  23308. * @param b The second submesh
  23309. * @returns The result of the comparison
  23310. */
  23311. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23312. // Then distance to camera
  23313. if (a._distanceToCamera < b._distanceToCamera) {
  23314. return 1;
  23315. }
  23316. if (a._distanceToCamera > b._distanceToCamera) {
  23317. return -1;
  23318. }
  23319. return 0;
  23320. };
  23321. /**
  23322. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23323. * are rendered front to back (prevent overdraw).
  23324. *
  23325. * @param a The first submesh
  23326. * @param b The second submesh
  23327. * @returns The result of the comparison
  23328. */
  23329. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23330. // Then distance to camera
  23331. if (a._distanceToCamera < b._distanceToCamera) {
  23332. return -1;
  23333. }
  23334. if (a._distanceToCamera > b._distanceToCamera) {
  23335. return 1;
  23336. }
  23337. return 0;
  23338. };
  23339. /**
  23340. * Resets the different lists of submeshes to prepare a new frame.
  23341. */
  23342. RenderingGroup.prototype.prepare = function () {
  23343. this._opaqueSubMeshes.reset();
  23344. this._transparentSubMeshes.reset();
  23345. this._alphaTestSubMeshes.reset();
  23346. this._depthOnlySubMeshes.reset();
  23347. this._particleSystems.reset();
  23348. this._spriteManagers.reset();
  23349. this._edgesRenderers.reset();
  23350. };
  23351. RenderingGroup.prototype.dispose = function () {
  23352. this._opaqueSubMeshes.dispose();
  23353. this._transparentSubMeshes.dispose();
  23354. this._alphaTestSubMeshes.dispose();
  23355. this._depthOnlySubMeshes.dispose();
  23356. this._particleSystems.dispose();
  23357. this._spriteManagers.dispose();
  23358. this._edgesRenderers.dispose();
  23359. };
  23360. /**
  23361. * Inserts the submesh in its correct queue depending on its material.
  23362. * @param subMesh The submesh to dispatch
  23363. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23364. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23365. */
  23366. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23367. // Get mesh and materials if not provided
  23368. if (mesh === undefined) {
  23369. mesh = subMesh.getMesh();
  23370. }
  23371. if (material === undefined) {
  23372. material = subMesh.getMaterial();
  23373. }
  23374. if (material === null || material === undefined) {
  23375. return;
  23376. }
  23377. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23378. this._transparentSubMeshes.push(subMesh);
  23379. }
  23380. else if (material.needAlphaTesting()) { // Alpha test
  23381. if (material.needDepthPrePass) {
  23382. this._depthOnlySubMeshes.push(subMesh);
  23383. }
  23384. this._alphaTestSubMeshes.push(subMesh);
  23385. }
  23386. else {
  23387. if (material.needDepthPrePass) {
  23388. this._depthOnlySubMeshes.push(subMesh);
  23389. }
  23390. this._opaqueSubMeshes.push(subMesh); // Opaque
  23391. }
  23392. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23393. this._edgesRenderers.push(mesh._edgesRenderer);
  23394. }
  23395. };
  23396. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23397. this._spriteManagers.push(spriteManager);
  23398. };
  23399. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23400. this._particleSystems.push(particleSystem);
  23401. };
  23402. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23403. if (this._particleSystems.length === 0) {
  23404. return;
  23405. }
  23406. // Particles
  23407. var activeCamera = this._scene.activeCamera;
  23408. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23409. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23410. var particleSystem = this._particleSystems.data[particleIndex];
  23411. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23412. continue;
  23413. }
  23414. var emitter = particleSystem.emitter;
  23415. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23416. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23417. }
  23418. }
  23419. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23420. };
  23421. RenderingGroup.prototype._renderSprites = function () {
  23422. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23423. return;
  23424. }
  23425. // Sprites
  23426. var activeCamera = this._scene.activeCamera;
  23427. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23428. for (var id = 0; id < this._spriteManagers.length; id++) {
  23429. var spriteManager = this._spriteManagers.data[id];
  23430. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23431. spriteManager.render();
  23432. }
  23433. }
  23434. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23435. };
  23436. return RenderingGroup;
  23437. }());
  23438. BABYLON.RenderingGroup = RenderingGroup;
  23439. })(BABYLON || (BABYLON = {}));
  23440. //# sourceMappingURL=babylon.renderingGroup.js.map
  23441. var BABYLON;
  23442. (function (BABYLON) {
  23443. /** @hidden */
  23444. var ClickInfo = /** @class */ (function () {
  23445. function ClickInfo() {
  23446. this._singleClick = false;
  23447. this._doubleClick = false;
  23448. this._hasSwiped = false;
  23449. this._ignore = false;
  23450. }
  23451. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23452. get: function () {
  23453. return this._singleClick;
  23454. },
  23455. set: function (b) {
  23456. this._singleClick = b;
  23457. },
  23458. enumerable: true,
  23459. configurable: true
  23460. });
  23461. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23462. get: function () {
  23463. return this._doubleClick;
  23464. },
  23465. set: function (b) {
  23466. this._doubleClick = b;
  23467. },
  23468. enumerable: true,
  23469. configurable: true
  23470. });
  23471. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23472. get: function () {
  23473. return this._hasSwiped;
  23474. },
  23475. set: function (b) {
  23476. this._hasSwiped = b;
  23477. },
  23478. enumerable: true,
  23479. configurable: true
  23480. });
  23481. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23482. get: function () {
  23483. return this._ignore;
  23484. },
  23485. set: function (b) {
  23486. this._ignore = b;
  23487. },
  23488. enumerable: true,
  23489. configurable: true
  23490. });
  23491. return ClickInfo;
  23492. }());
  23493. /**
  23494. * This class is used by the onRenderingGroupObservable
  23495. */
  23496. var RenderingGroupInfo = /** @class */ (function () {
  23497. function RenderingGroupInfo() {
  23498. }
  23499. /**
  23500. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23501. * This stage will be fired no matter what
  23502. */
  23503. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23504. /**
  23505. * Called before opaque object are rendered.
  23506. * This stage will be fired only if there's 3D Opaque content to render
  23507. */
  23508. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23509. /**
  23510. * Called after the opaque objects are rendered and before the transparent ones
  23511. * This stage will be fired only if there's 3D transparent content to render
  23512. */
  23513. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23514. /**
  23515. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23516. * This stage will be fired no matter what
  23517. */
  23518. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23519. return RenderingGroupInfo;
  23520. }());
  23521. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23522. /**
  23523. * Represents a scene to be rendered by the engine.
  23524. * @see http://doc.babylonjs.com/features/scene
  23525. */
  23526. var Scene = /** @class */ (function () {
  23527. /**
  23528. * Creates a new Scene
  23529. * @param engine defines the engine to use to render this scene
  23530. */
  23531. function Scene(engine) {
  23532. // Members
  23533. /**
  23534. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23535. */
  23536. this.autoClear = true;
  23537. /**
  23538. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23539. */
  23540. this.autoClearDepthAndStencil = true;
  23541. /**
  23542. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23543. */
  23544. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23545. /**
  23546. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23547. */
  23548. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23549. this._forceWireframe = false;
  23550. this._forcePointsCloud = false;
  23551. /**
  23552. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23553. */
  23554. this.forceShowBoundingBoxes = false;
  23555. /**
  23556. * Gets or sets a boolean indicating if animations are enabled
  23557. */
  23558. this.animationsEnabled = true;
  23559. this._animationPropertiesOverride = null;
  23560. /**
  23561. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23562. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23563. */
  23564. this.useConstantAnimationDeltaTime = false;
  23565. /**
  23566. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23567. * Please note that it requires to run a ray cast through the scene on every frame
  23568. */
  23569. this.constantlyUpdateMeshUnderPointer = false;
  23570. /**
  23571. * Defines the HTML cursor to use when hovering over interactive elements
  23572. */
  23573. this.hoverCursor = "pointer";
  23574. /**
  23575. * Defines the HTML default cursor to use (empty by default)
  23576. */
  23577. this.defaultCursor = "";
  23578. /**
  23579. * This is used to call preventDefault() on pointer down
  23580. * in order to block unwanted artifacts like system double clicks
  23581. */
  23582. this.preventDefaultOnPointerDown = true;
  23583. // Metadata
  23584. /**
  23585. * Gets or sets user defined metadata
  23586. */
  23587. this.metadata = null;
  23588. /**
  23589. * Use this array to add regular expressions used to disable offline support for specific urls
  23590. */
  23591. this.disableOfflineSupportExceptionRules = new Array();
  23592. /**
  23593. * An event triggered when the scene is disposed.
  23594. */
  23595. this.onDisposeObservable = new BABYLON.Observable();
  23596. this._onDisposeObserver = null;
  23597. /**
  23598. * An event triggered before rendering the scene (right after animations and physics)
  23599. */
  23600. this.onBeforeRenderObservable = new BABYLON.Observable();
  23601. this._onBeforeRenderObserver = null;
  23602. /**
  23603. * An event triggered after rendering the scene
  23604. */
  23605. this.onAfterRenderObservable = new BABYLON.Observable();
  23606. this._onAfterRenderObserver = null;
  23607. /**
  23608. * An event triggered before animating the scene
  23609. */
  23610. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23611. /**
  23612. * An event triggered after animations processing
  23613. */
  23614. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23615. /**
  23616. * An event triggered before draw calls are ready to be sent
  23617. */
  23618. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23619. /**
  23620. * An event triggered after draw calls have been sent
  23621. */
  23622. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23623. /**
  23624. * An event triggered when physic simulation is about to be run
  23625. */
  23626. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23627. /**
  23628. * An event triggered when physic simulation has been done
  23629. */
  23630. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23631. /**
  23632. * An event triggered when the scene is ready
  23633. */
  23634. this.onReadyObservable = new BABYLON.Observable();
  23635. /**
  23636. * An event triggered before rendering a camera
  23637. */
  23638. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23639. this._onBeforeCameraRenderObserver = null;
  23640. /**
  23641. * An event triggered after rendering a camera
  23642. */
  23643. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23644. this._onAfterCameraRenderObserver = null;
  23645. /**
  23646. * An event triggered when active meshes evaluation is about to start
  23647. */
  23648. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23649. /**
  23650. * An event triggered when active meshes evaluation is done
  23651. */
  23652. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23653. /**
  23654. * An event triggered when particles rendering is about to start
  23655. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23656. */
  23657. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23658. /**
  23659. * An event triggered when particles rendering is done
  23660. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23661. */
  23662. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23663. /**
  23664. * An event triggered when sprites rendering is about to start
  23665. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23666. */
  23667. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23668. /**
  23669. * An event triggered when sprites rendering is done
  23670. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23671. */
  23672. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23673. /**
  23674. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23675. */
  23676. this.onDataLoadedObservable = new BABYLON.Observable();
  23677. /**
  23678. * An event triggered when a camera is created
  23679. */
  23680. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23681. /**
  23682. * An event triggered when a camera is removed
  23683. */
  23684. this.onCameraRemovedObservable = new BABYLON.Observable();
  23685. /**
  23686. * An event triggered when a light is created
  23687. */
  23688. this.onNewLightAddedObservable = new BABYLON.Observable();
  23689. /**
  23690. * An event triggered when a light is removed
  23691. */
  23692. this.onLightRemovedObservable = new BABYLON.Observable();
  23693. /**
  23694. * An event triggered when a geometry is created
  23695. */
  23696. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23697. /**
  23698. * An event triggered when a geometry is removed
  23699. */
  23700. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23701. /**
  23702. * An event triggered when a transform node is created
  23703. */
  23704. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23705. /**
  23706. * An event triggered when a transform node is removed
  23707. */
  23708. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23709. /**
  23710. * An event triggered when a mesh is created
  23711. */
  23712. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23713. /**
  23714. * An event triggered when a mesh is removed
  23715. */
  23716. this.onMeshRemovedObservable = new BABYLON.Observable();
  23717. /**
  23718. * An event triggered when render targets are about to be rendered
  23719. * Can happen multiple times per frame.
  23720. */
  23721. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23722. /**
  23723. * An event triggered when render targets were rendered.
  23724. * Can happen multiple times per frame.
  23725. */
  23726. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23727. /**
  23728. * An event triggered before calculating deterministic simulation step
  23729. */
  23730. this.onBeforeStepObservable = new BABYLON.Observable();
  23731. /**
  23732. * An event triggered after calculating deterministic simulation step
  23733. */
  23734. this.onAfterStepObservable = new BABYLON.Observable();
  23735. /**
  23736. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23737. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23738. * 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)
  23739. */
  23740. this.onRenderingGroupObservable = new BABYLON.Observable();
  23741. // Animations
  23742. /**
  23743. * Gets a list of Animations associated with the scene
  23744. */
  23745. this.animations = [];
  23746. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23747. /**
  23748. * 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).
  23749. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23750. */
  23751. this.onPrePointerObservable = new BABYLON.Observable();
  23752. /**
  23753. * Observable event triggered each time an input event is received from the rendering canvas
  23754. */
  23755. this.onPointerObservable = new BABYLON.Observable();
  23756. this._meshPickProceed = false;
  23757. this._currentPickResult = null;
  23758. this._previousPickResult = null;
  23759. this._totalPointersPressed = 0;
  23760. this._doubleClickOccured = false;
  23761. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23762. this.cameraToUseForPointers = null;
  23763. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23764. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23765. this._startingPointerTime = 0;
  23766. this._previousStartingPointerTime = 0;
  23767. // Deterministic lockstep
  23768. this._timeAccumulator = 0;
  23769. this._currentStepId = 0;
  23770. this._currentInternalStep = 0;
  23771. // Keyboard
  23772. /**
  23773. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23774. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23775. */
  23776. this.onPreKeyboardObservable = new BABYLON.Observable();
  23777. /**
  23778. * Observable event triggered each time an keyboard event is received from the hosting window
  23779. */
  23780. this.onKeyboardObservable = new BABYLON.Observable();
  23781. // Coordinates system
  23782. this._useRightHandedSystem = false;
  23783. // Fog
  23784. this._fogEnabled = true;
  23785. this._fogMode = Scene.FOGMODE_NONE;
  23786. /**
  23787. * Gets or sets the fog color to use
  23788. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23789. */
  23790. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23791. /**
  23792. * Gets or sets the fog density to use
  23793. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23794. */
  23795. this.fogDensity = 0.1;
  23796. /**
  23797. * Gets or sets the fog start distance to use
  23798. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23799. */
  23800. this.fogStart = 0;
  23801. /**
  23802. * Gets or sets the fog end distance to use
  23803. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23804. */
  23805. this.fogEnd = 1000.0;
  23806. // Lights
  23807. this._shadowsEnabled = true;
  23808. this._lightsEnabled = true;
  23809. /**
  23810. * All of the lights added to this scene
  23811. * @see http://doc.babylonjs.com/babylon101/lights
  23812. */
  23813. this.lights = new Array();
  23814. // Cameras
  23815. /** All of the cameras added to this scene.
  23816. * @see http://doc.babylonjs.com/babylon101/cameras
  23817. */
  23818. this.cameras = new Array();
  23819. /** All of the active cameras added to this scene. */
  23820. this.activeCameras = new Array();
  23821. // Meshes
  23822. /**
  23823. * All of the tranform nodes added to this scene
  23824. * @see http://doc.babylonjs.com/how_to/transformnode
  23825. */
  23826. this.transformNodes = new Array();
  23827. /**
  23828. * All of the (abstract) meshes added to this scene
  23829. */
  23830. this.meshes = new Array();
  23831. /**
  23832. * All of the animation groups added to this scene
  23833. * @see http://doc.babylonjs.com/how_to/group
  23834. */
  23835. this.animationGroups = new Array();
  23836. // Geometries
  23837. this._geometries = new Array();
  23838. /**
  23839. * All of the materials added to this scene
  23840. * @see http://doc.babylonjs.com/babylon101/materials
  23841. */
  23842. this.materials = new Array();
  23843. /**
  23844. * All of the multi-materials added to this scene
  23845. * @see http://doc.babylonjs.com/how_to/multi_materials
  23846. */
  23847. this.multiMaterials = new Array();
  23848. // Textures
  23849. this._texturesEnabled = true;
  23850. /**
  23851. * All of the textures added to this scene
  23852. */
  23853. this.textures = new Array();
  23854. // Particles
  23855. /**
  23856. * Gets or sets a boolean indicating if particles are enabled on this scene
  23857. */
  23858. this.particlesEnabled = true;
  23859. /**
  23860. * All of the particle systems added to this scene
  23861. * @see http://doc.babylonjs.com/babylon101/particles
  23862. */
  23863. this.particleSystems = new Array();
  23864. // Sprites
  23865. /**
  23866. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23867. */
  23868. this.spritesEnabled = true;
  23869. /**
  23870. * All of the sprite managers added to this scene
  23871. * @see http://doc.babylonjs.com/babylon101/sprites
  23872. */
  23873. this.spriteManagers = new Array();
  23874. /**
  23875. * The list of layers (background and foreground) of the scene
  23876. */
  23877. this.layers = new Array();
  23878. /**
  23879. * The list of effect layers (highlights/glow) added to the scene
  23880. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23881. * @see http://doc.babylonjs.com/how_to/glow_layer
  23882. */
  23883. this.effectLayers = new Array();
  23884. // Skeletons
  23885. this._skeletonsEnabled = true;
  23886. /**
  23887. * The list of skeletons added to the scene
  23888. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23889. */
  23890. this.skeletons = new Array();
  23891. // Morph targets
  23892. /**
  23893. * The list of morph target managers added to the scene
  23894. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23895. */
  23896. this.morphTargetManagers = new Array();
  23897. // Lens flares
  23898. /**
  23899. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23900. */
  23901. this.lensFlaresEnabled = true;
  23902. /**
  23903. * The list of lens flare system added to the scene
  23904. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23905. */
  23906. this.lensFlareSystems = new Array();
  23907. // Collisions
  23908. /**
  23909. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23910. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23911. */
  23912. this.collisionsEnabled = true;
  23913. /**
  23914. * Defines the gravity applied to this scene (used only for collisions)
  23915. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23916. */
  23917. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23918. // Postprocesses
  23919. /**
  23920. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23921. */
  23922. this.postProcessesEnabled = true;
  23923. /**
  23924. * The list of postprocesses added to the scene
  23925. */
  23926. this.postProcesses = new Array();
  23927. // Customs render targets
  23928. /**
  23929. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23930. */
  23931. this.renderTargetsEnabled = true;
  23932. /**
  23933. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23934. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23935. */
  23936. this.dumpNextRenderTargets = false;
  23937. /**
  23938. * The list of user defined render targets added to the scene
  23939. */
  23940. this.customRenderTargets = new Array();
  23941. /**
  23942. * Gets the list of meshes imported to the scene through SceneLoader
  23943. */
  23944. this.importedMeshesFiles = new Array();
  23945. // Probes
  23946. /**
  23947. * Gets or sets a boolean indicating if probes are enabled on this scene
  23948. */
  23949. this.probesEnabled = true;
  23950. /**
  23951. * The list of reflection probes added to the scene
  23952. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23953. */
  23954. this.reflectionProbes = new Array();
  23955. /** @hidden */
  23956. this._actionManagers = new Array();
  23957. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23958. // Procedural textures
  23959. /**
  23960. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23961. */
  23962. this.proceduralTexturesEnabled = true;
  23963. /**
  23964. * The list of procedural textures added to the scene
  23965. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23966. */
  23967. this.proceduralTextures = new Array();
  23968. /**
  23969. * The list of sound tracks added to the scene
  23970. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23971. */
  23972. this.soundTracks = new Array();
  23973. this._audioEnabled = true;
  23974. this._headphone = false;
  23975. // Performance counters
  23976. this._totalVertices = new BABYLON.PerfCounter();
  23977. /** @hidden */
  23978. this._activeIndices = new BABYLON.PerfCounter();
  23979. /** @hidden */
  23980. this._activeParticles = new BABYLON.PerfCounter();
  23981. /** @hidden */
  23982. this._activeBones = new BABYLON.PerfCounter();
  23983. this._animationTime = 0;
  23984. /**
  23985. * Gets or sets a general scale for animation speed
  23986. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23987. */
  23988. this.animationTimeScale = 1;
  23989. this._renderId = 0;
  23990. this._executeWhenReadyTimeoutId = -1;
  23991. this._intermediateRendering = false;
  23992. this._viewUpdateFlag = -1;
  23993. this._projectionUpdateFlag = -1;
  23994. this._alternateViewUpdateFlag = -1;
  23995. this._alternateProjectionUpdateFlag = -1;
  23996. /** @hidden */
  23997. this._toBeDisposed = new BABYLON.SmartArray(256);
  23998. this._activeRequests = new Array();
  23999. this._pendingData = new Array();
  24000. this._isDisposed = false;
  24001. /**
  24002. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24003. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24004. */
  24005. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24006. this._activeMeshes = new BABYLON.SmartArray(256);
  24007. this._processedMaterials = new BABYLON.SmartArray(256);
  24008. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24009. /** @hidden */
  24010. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24011. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24012. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24013. /** @hidden */
  24014. this._activeAnimatables = new Array();
  24015. this._transformMatrix = BABYLON.Matrix.Zero();
  24016. this._useAlternateCameraConfiguration = false;
  24017. this._alternateRendering = false;
  24018. /**
  24019. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24020. * This is useful if there are more lights that the maximum simulteanous authorized
  24021. */
  24022. this.requireLightSorting = false;
  24023. this._depthRenderer = {};
  24024. this._activeMeshesFrozen = false;
  24025. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24026. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24027. this._engine.scenes.push(this);
  24028. this._uid = null;
  24029. this._renderingManager = new BABYLON.RenderingManager(this);
  24030. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24031. if (BABYLON.OutlineRenderer) {
  24032. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24033. }
  24034. if (BABYLON.Tools.IsWindowObjectExist()) {
  24035. this.attachControl();
  24036. }
  24037. //simplification queue
  24038. if (BABYLON.SimplificationQueue) {
  24039. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24040. }
  24041. //collision coordinator initialization. For now legacy per default.
  24042. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24043. // Uniform Buffer
  24044. this._createUbo();
  24045. // Default Image processing definition.
  24046. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24047. }
  24048. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24049. /** The fog is deactivated */
  24050. get: function () {
  24051. return Scene._FOGMODE_NONE;
  24052. },
  24053. enumerable: true,
  24054. configurable: true
  24055. });
  24056. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24057. /** The fog density is following an exponential function */
  24058. get: function () {
  24059. return Scene._FOGMODE_EXP;
  24060. },
  24061. enumerable: true,
  24062. configurable: true
  24063. });
  24064. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24065. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24066. get: function () {
  24067. return Scene._FOGMODE_EXP2;
  24068. },
  24069. enumerable: true,
  24070. configurable: true
  24071. });
  24072. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24073. /** The fog density is following a linear function. */
  24074. get: function () {
  24075. return Scene._FOGMODE_LINEAR;
  24076. },
  24077. enumerable: true,
  24078. configurable: true
  24079. });
  24080. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24081. /**
  24082. * Texture used in all pbr material as the reflection texture.
  24083. * As in the majority of the scene they are the same (exception for multi room and so on),
  24084. * this is easier to reference from here than from all the materials.
  24085. */
  24086. get: function () {
  24087. return this._environmentTexture;
  24088. },
  24089. /**
  24090. * Texture used in all pbr material as the reflection texture.
  24091. * As in the majority of the scene they are the same (exception for multi room and so on),
  24092. * this is easier to set here than in all the materials.
  24093. */
  24094. set: function (value) {
  24095. if (this._environmentTexture === value) {
  24096. return;
  24097. }
  24098. this._environmentTexture = value;
  24099. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24100. },
  24101. enumerable: true,
  24102. configurable: true
  24103. });
  24104. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24105. /**
  24106. * Default image processing configuration used either in the rendering
  24107. * Forward main pass or through the imageProcessingPostProcess if present.
  24108. * As in the majority of the scene they are the same (exception for multi camera),
  24109. * this is easier to reference from here than from all the materials and post process.
  24110. *
  24111. * No setter as we it is a shared configuration, you can set the values instead.
  24112. */
  24113. get: function () {
  24114. return this._imageProcessingConfiguration;
  24115. },
  24116. enumerable: true,
  24117. configurable: true
  24118. });
  24119. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24120. get: function () {
  24121. return this._forceWireframe;
  24122. },
  24123. /**
  24124. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24125. */
  24126. set: function (value) {
  24127. if (this._forceWireframe === value) {
  24128. return;
  24129. }
  24130. this._forceWireframe = value;
  24131. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24132. },
  24133. enumerable: true,
  24134. configurable: true
  24135. });
  24136. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24137. get: function () {
  24138. return this._forcePointsCloud;
  24139. },
  24140. /**
  24141. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24142. */
  24143. set: function (value) {
  24144. if (this._forcePointsCloud === value) {
  24145. return;
  24146. }
  24147. this._forcePointsCloud = value;
  24148. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24149. },
  24150. enumerable: true,
  24151. configurable: true
  24152. });
  24153. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24154. /**
  24155. * Gets or sets the animation properties override
  24156. */
  24157. get: function () {
  24158. return this._animationPropertiesOverride;
  24159. },
  24160. set: function (value) {
  24161. this._animationPropertiesOverride = value;
  24162. },
  24163. enumerable: true,
  24164. configurable: true
  24165. });
  24166. Object.defineProperty(Scene.prototype, "onDispose", {
  24167. /** Sets a function to be executed when this scene is disposed. */
  24168. set: function (callback) {
  24169. if (this._onDisposeObserver) {
  24170. this.onDisposeObservable.remove(this._onDisposeObserver);
  24171. }
  24172. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24173. },
  24174. enumerable: true,
  24175. configurable: true
  24176. });
  24177. Object.defineProperty(Scene.prototype, "beforeRender", {
  24178. /** Sets a function to be executed before rendering this scene */
  24179. set: function (callback) {
  24180. if (this._onBeforeRenderObserver) {
  24181. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24182. }
  24183. if (callback) {
  24184. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24185. }
  24186. },
  24187. enumerable: true,
  24188. configurable: true
  24189. });
  24190. Object.defineProperty(Scene.prototype, "afterRender", {
  24191. /** Sets a function to be executed after rendering this scene */
  24192. set: function (callback) {
  24193. if (this._onAfterRenderObserver) {
  24194. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24195. }
  24196. if (callback) {
  24197. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24198. }
  24199. },
  24200. enumerable: true,
  24201. configurable: true
  24202. });
  24203. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24204. /** Sets a function to be executed before rendering a camera*/
  24205. set: function (callback) {
  24206. if (this._onBeforeCameraRenderObserver) {
  24207. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24208. }
  24209. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24210. },
  24211. enumerable: true,
  24212. configurable: true
  24213. });
  24214. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24215. /** Sets a function to be executed after rendering a camera*/
  24216. set: function (callback) {
  24217. if (this._onAfterCameraRenderObserver) {
  24218. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24219. }
  24220. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24226. /**
  24227. * Gets the gamepad manager associated with the scene
  24228. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24229. */
  24230. get: function () {
  24231. if (!this._gamepadManager) {
  24232. this._gamepadManager = new BABYLON.GamepadManager(this);
  24233. }
  24234. return this._gamepadManager;
  24235. },
  24236. enumerable: true,
  24237. configurable: true
  24238. });
  24239. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24240. /**
  24241. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24242. */
  24243. get: function () {
  24244. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24245. },
  24246. enumerable: true,
  24247. configurable: true
  24248. });
  24249. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24250. get: function () {
  24251. return this._useRightHandedSystem;
  24252. },
  24253. /**
  24254. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24255. */
  24256. set: function (value) {
  24257. if (this._useRightHandedSystem === value) {
  24258. return;
  24259. }
  24260. this._useRightHandedSystem = value;
  24261. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24262. },
  24263. enumerable: true,
  24264. configurable: true
  24265. });
  24266. /**
  24267. * Sets the step Id used by deterministic lock step
  24268. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24269. * @param newStepId defines the step Id
  24270. */
  24271. Scene.prototype.setStepId = function (newStepId) {
  24272. this._currentStepId = newStepId;
  24273. };
  24274. ;
  24275. /**
  24276. * Gets the step Id used by deterministic lock step
  24277. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24278. * @returns the step Id
  24279. */
  24280. Scene.prototype.getStepId = function () {
  24281. return this._currentStepId;
  24282. };
  24283. ;
  24284. /**
  24285. * Gets the internal step used by deterministic lock step
  24286. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24287. * @returns the internal step
  24288. */
  24289. Scene.prototype.getInternalStep = function () {
  24290. return this._currentInternalStep;
  24291. };
  24292. ;
  24293. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24294. get: function () {
  24295. return this._fogEnabled;
  24296. },
  24297. /**
  24298. * Gets or sets a boolean indicating if fog is enabled on this scene
  24299. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24300. */
  24301. set: function (value) {
  24302. if (this._fogEnabled === value) {
  24303. return;
  24304. }
  24305. this._fogEnabled = value;
  24306. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24307. },
  24308. enumerable: true,
  24309. configurable: true
  24310. });
  24311. Object.defineProperty(Scene.prototype, "fogMode", {
  24312. get: function () {
  24313. return this._fogMode;
  24314. },
  24315. /**
  24316. * Gets or sets the fog mode to use
  24317. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24318. */
  24319. set: function (value) {
  24320. if (this._fogMode === value) {
  24321. return;
  24322. }
  24323. this._fogMode = value;
  24324. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24330. get: function () {
  24331. return this._shadowsEnabled;
  24332. },
  24333. /**
  24334. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24335. */
  24336. set: function (value) {
  24337. if (this._shadowsEnabled === value) {
  24338. return;
  24339. }
  24340. this._shadowsEnabled = value;
  24341. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24342. },
  24343. enumerable: true,
  24344. configurable: true
  24345. });
  24346. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24347. get: function () {
  24348. return this._lightsEnabled;
  24349. },
  24350. /**
  24351. * Gets or sets a boolean indicating if lights are enabled on this scene
  24352. */
  24353. set: function (value) {
  24354. if (this._lightsEnabled === value) {
  24355. return;
  24356. }
  24357. this._lightsEnabled = value;
  24358. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24359. },
  24360. enumerable: true,
  24361. configurable: true
  24362. });
  24363. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24364. /** The default material used on meshes when no material is affected */
  24365. get: function () {
  24366. if (!this._defaultMaterial) {
  24367. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24368. }
  24369. return this._defaultMaterial;
  24370. },
  24371. /** The default material used on meshes when no material is affected */
  24372. set: function (value) {
  24373. this._defaultMaterial = value;
  24374. },
  24375. enumerable: true,
  24376. configurable: true
  24377. });
  24378. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24379. get: function () {
  24380. return this._texturesEnabled;
  24381. },
  24382. /**
  24383. * Gets or sets a boolean indicating if textures are enabled on this scene
  24384. */
  24385. set: function (value) {
  24386. if (this._texturesEnabled === value) {
  24387. return;
  24388. }
  24389. this._texturesEnabled = value;
  24390. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24391. },
  24392. enumerable: true,
  24393. configurable: true
  24394. });
  24395. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24396. get: function () {
  24397. return this._skeletonsEnabled;
  24398. },
  24399. /**
  24400. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24401. */
  24402. set: function (value) {
  24403. if (this._skeletonsEnabled === value) {
  24404. return;
  24405. }
  24406. this._skeletonsEnabled = value;
  24407. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24408. },
  24409. enumerable: true,
  24410. configurable: true
  24411. });
  24412. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24413. /**
  24414. * Gets the postprocess render pipeline manager
  24415. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24416. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24417. */
  24418. get: function () {
  24419. if (!this._postProcessRenderPipelineManager) {
  24420. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24421. }
  24422. return this._postProcessRenderPipelineManager;
  24423. },
  24424. enumerable: true,
  24425. configurable: true
  24426. });
  24427. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24428. /**
  24429. * Gets the main soundtrack associated with the scene
  24430. */
  24431. get: function () {
  24432. if (!this._mainSoundTrack) {
  24433. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24434. }
  24435. return this._mainSoundTrack;
  24436. },
  24437. enumerable: true,
  24438. configurable: true
  24439. });
  24440. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24441. /** @hidden */
  24442. get: function () {
  24443. return this._alternateRendering;
  24444. },
  24445. enumerable: true,
  24446. configurable: true
  24447. });
  24448. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24449. /**
  24450. * Gets the list of frustum planes (built from the active camera)
  24451. */
  24452. get: function () {
  24453. return this._frustumPlanes;
  24454. },
  24455. enumerable: true,
  24456. configurable: true
  24457. });
  24458. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24459. /**
  24460. * Gets the current geometry buffer associated to the scene.
  24461. */
  24462. get: function () {
  24463. return this._geometryBufferRenderer;
  24464. },
  24465. /**
  24466. * Sets the current geometry buffer for the scene.
  24467. */
  24468. set: function (geometryBufferRenderer) {
  24469. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24470. this._geometryBufferRenderer = geometryBufferRenderer;
  24471. }
  24472. },
  24473. enumerable: true,
  24474. configurable: true
  24475. });
  24476. Object.defineProperty(Scene.prototype, "debugLayer", {
  24477. /**
  24478. * Gets the debug layer associated with the scene
  24479. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24480. */
  24481. get: function () {
  24482. if (!this._debugLayer) {
  24483. this._debugLayer = new BABYLON.DebugLayer(this);
  24484. }
  24485. return this._debugLayer;
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24491. /**
  24492. * Gets a boolean indicating if collisions are processed on a web worker
  24493. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24494. */
  24495. get: function () {
  24496. return this._workerCollisions;
  24497. },
  24498. set: function (enabled) {
  24499. if (!BABYLON.CollisionCoordinatorLegacy) {
  24500. return;
  24501. }
  24502. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24503. this._workerCollisions = enabled;
  24504. if (this.collisionCoordinator) {
  24505. this.collisionCoordinator.destroy();
  24506. }
  24507. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24508. this.collisionCoordinator.init(this);
  24509. },
  24510. enumerable: true,
  24511. configurable: true
  24512. });
  24513. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24514. /**
  24515. * Gets the octree used to boost mesh selection (picking)
  24516. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24517. */
  24518. get: function () {
  24519. return this._selectionOctree;
  24520. },
  24521. enumerable: true,
  24522. configurable: true
  24523. });
  24524. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24525. /**
  24526. * Gets the mesh that is currently under the pointer
  24527. */
  24528. get: function () {
  24529. return this._pointerOverMesh;
  24530. },
  24531. enumerable: true,
  24532. configurable: true
  24533. });
  24534. Object.defineProperty(Scene.prototype, "pointerX", {
  24535. /**
  24536. * Gets the current on-screen X position of the pointer
  24537. */
  24538. get: function () {
  24539. return this._pointerX;
  24540. },
  24541. enumerable: true,
  24542. configurable: true
  24543. });
  24544. Object.defineProperty(Scene.prototype, "pointerY", {
  24545. /**
  24546. * Gets the current on-screen Y position of the pointer
  24547. */
  24548. get: function () {
  24549. return this._pointerY;
  24550. },
  24551. enumerable: true,
  24552. configurable: true
  24553. });
  24554. /**
  24555. * Gets the cached material (ie. the latest rendered one)
  24556. * @returns the cached material
  24557. */
  24558. Scene.prototype.getCachedMaterial = function () {
  24559. return this._cachedMaterial;
  24560. };
  24561. /**
  24562. * Gets the cached effect (ie. the latest rendered one)
  24563. * @returns the cached effect
  24564. */
  24565. Scene.prototype.getCachedEffect = function () {
  24566. return this._cachedEffect;
  24567. };
  24568. /**
  24569. * Gets the cached visibility state (ie. the latest rendered one)
  24570. * @returns the cached visibility state
  24571. */
  24572. Scene.prototype.getCachedVisibility = function () {
  24573. return this._cachedVisibility;
  24574. };
  24575. /**
  24576. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24577. * @param material defines the current material
  24578. * @param effect defines the current effect
  24579. * @param visibility defines the current visibility state
  24580. * @returns true if one parameter is not cached
  24581. */
  24582. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24583. if (visibility === void 0) { visibility = 1; }
  24584. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24585. };
  24586. /**
  24587. * Gets the bounding box renderer associated with the scene
  24588. * @returns a BoundingBoxRenderer
  24589. */
  24590. Scene.prototype.getBoundingBoxRenderer = function () {
  24591. if (!this._boundingBoxRenderer) {
  24592. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24593. }
  24594. return this._boundingBoxRenderer;
  24595. };
  24596. /**
  24597. * Gets the outline renderer associated with the scene
  24598. * @returns a OutlineRenderer
  24599. */
  24600. Scene.prototype.getOutlineRenderer = function () {
  24601. return this._outlineRenderer;
  24602. };
  24603. /**
  24604. * Gets the engine associated with the scene
  24605. * @returns an Engine
  24606. */
  24607. Scene.prototype.getEngine = function () {
  24608. return this._engine;
  24609. };
  24610. /**
  24611. * Gets the total number of vertices rendered per frame
  24612. * @returns the total number of vertices rendered per frame
  24613. */
  24614. Scene.prototype.getTotalVertices = function () {
  24615. return this._totalVertices.current;
  24616. };
  24617. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24618. /**
  24619. * Gets the performance counter for total vertices
  24620. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24621. */
  24622. get: function () {
  24623. return this._totalVertices;
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. /**
  24629. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24630. * @returns the total number of active indices rendered per frame
  24631. */
  24632. Scene.prototype.getActiveIndices = function () {
  24633. return this._activeIndices.current;
  24634. };
  24635. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24636. /**
  24637. * Gets the performance counter for active indices
  24638. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24639. */
  24640. get: function () {
  24641. return this._activeIndices;
  24642. },
  24643. enumerable: true,
  24644. configurable: true
  24645. });
  24646. /**
  24647. * Gets the total number of active particles rendered per frame
  24648. * @returns the total number of active particles rendered per frame
  24649. */
  24650. Scene.prototype.getActiveParticles = function () {
  24651. return this._activeParticles.current;
  24652. };
  24653. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24654. /**
  24655. * Gets the performance counter for active particles
  24656. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24657. */
  24658. get: function () {
  24659. return this._activeParticles;
  24660. },
  24661. enumerable: true,
  24662. configurable: true
  24663. });
  24664. /**
  24665. * Gets the total number of active bones rendered per frame
  24666. * @returns the total number of active bones rendered per frame
  24667. */
  24668. Scene.prototype.getActiveBones = function () {
  24669. return this._activeBones.current;
  24670. };
  24671. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24672. /**
  24673. * Gets the performance counter for active bones
  24674. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24675. */
  24676. get: function () {
  24677. return this._activeBones;
  24678. },
  24679. enumerable: true,
  24680. configurable: true
  24681. });
  24682. /** @hidden */
  24683. Scene.prototype.getInterFramePerfCounter = function () {
  24684. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24685. return 0;
  24686. };
  24687. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24688. /** @hidden */
  24689. get: function () {
  24690. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24691. return null;
  24692. },
  24693. enumerable: true,
  24694. configurable: true
  24695. });
  24696. /** @hidden */
  24697. Scene.prototype.getLastFrameDuration = function () {
  24698. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24699. return 0;
  24700. };
  24701. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24702. /** @hidden */
  24703. get: function () {
  24704. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24705. return null;
  24706. },
  24707. enumerable: true,
  24708. configurable: true
  24709. });
  24710. /** @hidden */
  24711. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24712. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24713. return 0;
  24714. };
  24715. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24716. /** @hidden */
  24717. get: function () {
  24718. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24719. return null;
  24720. },
  24721. enumerable: true,
  24722. configurable: true
  24723. });
  24724. /**
  24725. * Gets the array of active meshes
  24726. * @returns an array of AbstractMesh
  24727. */
  24728. Scene.prototype.getActiveMeshes = function () {
  24729. return this._activeMeshes;
  24730. };
  24731. /** @hidden */
  24732. Scene.prototype.getRenderTargetsDuration = function () {
  24733. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24734. return 0;
  24735. };
  24736. /** @hidden */
  24737. Scene.prototype.getRenderDuration = function () {
  24738. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24739. return 0;
  24740. };
  24741. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24742. /** @hidden */
  24743. get: function () {
  24744. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24745. return null;
  24746. },
  24747. enumerable: true,
  24748. configurable: true
  24749. });
  24750. /** @hidden */
  24751. Scene.prototype.getParticlesDuration = function () {
  24752. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24753. return 0;
  24754. };
  24755. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24756. /** @hidden */
  24757. get: function () {
  24758. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24759. return null;
  24760. },
  24761. enumerable: true,
  24762. configurable: true
  24763. });
  24764. /** @hidden */
  24765. Scene.prototype.getSpritesDuration = function () {
  24766. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24767. return 0;
  24768. };
  24769. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24770. /** @hidden */
  24771. get: function () {
  24772. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24773. return null;
  24774. },
  24775. enumerable: true,
  24776. configurable: true
  24777. });
  24778. /**
  24779. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24780. * @returns a number
  24781. */
  24782. Scene.prototype.getAnimationRatio = function () {
  24783. return this._animationRatio;
  24784. };
  24785. /**
  24786. * Gets an unique Id for the current frame
  24787. * @returns a number
  24788. */
  24789. Scene.prototype.getRenderId = function () {
  24790. return this._renderId;
  24791. };
  24792. /** Call this function if you want to manually increment the render Id*/
  24793. Scene.prototype.incrementRenderId = function () {
  24794. this._renderId++;
  24795. };
  24796. Scene.prototype._updatePointerPosition = function (evt) {
  24797. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24798. if (!canvasRect) {
  24799. return;
  24800. }
  24801. this._pointerX = evt.clientX - canvasRect.left;
  24802. this._pointerY = evt.clientY - canvasRect.top;
  24803. this._unTranslatedPointerX = this._pointerX;
  24804. this._unTranslatedPointerY = this._pointerY;
  24805. };
  24806. Scene.prototype._createUbo = function () {
  24807. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24808. this._sceneUbo.addUniform("viewProjection", 16);
  24809. this._sceneUbo.addUniform("view", 16);
  24810. };
  24811. Scene.prototype._createAlternateUbo = function () {
  24812. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24813. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24814. this._alternateSceneUbo.addUniform("view", 16);
  24815. };
  24816. // Pointers handling
  24817. /**
  24818. * Use this method to simulate a pointer move on a mesh
  24819. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24820. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24821. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24822. * @returns the current scene
  24823. */
  24824. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24825. var evt = new PointerEvent("pointermove", pointerEventInit);
  24826. return this._processPointerMove(pickResult, evt);
  24827. };
  24828. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24829. var canvas = this._engine.getRenderingCanvas();
  24830. if (!canvas) {
  24831. return this;
  24832. }
  24833. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24834. this.setPointerOverSprite(null);
  24835. this.setPointerOverMesh(pickResult.pickedMesh);
  24836. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24837. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24838. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24839. }
  24840. else {
  24841. canvas.style.cursor = this.hoverCursor;
  24842. }
  24843. }
  24844. else {
  24845. canvas.style.cursor = this.defaultCursor;
  24846. }
  24847. }
  24848. else {
  24849. this.setPointerOverMesh(null);
  24850. // Sprites
  24851. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24852. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24853. this.setPointerOverSprite(pickResult.pickedSprite);
  24854. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24855. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24856. }
  24857. else {
  24858. canvas.style.cursor = this.hoverCursor;
  24859. }
  24860. }
  24861. else {
  24862. this.setPointerOverSprite(null);
  24863. // Restore pointer
  24864. canvas.style.cursor = this.defaultCursor;
  24865. }
  24866. }
  24867. if (pickResult) {
  24868. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24869. if (this.onPointerMove) {
  24870. this.onPointerMove(evt, pickResult, type);
  24871. }
  24872. if (this.onPointerObservable.hasObservers()) {
  24873. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24874. this.onPointerObservable.notifyObservers(pi, type);
  24875. }
  24876. }
  24877. return this;
  24878. };
  24879. /**
  24880. * Use this method to simulate a pointer down on a mesh
  24881. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24882. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24883. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24884. * @returns the current scene
  24885. */
  24886. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24887. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24888. return this._processPointerDown(pickResult, evt);
  24889. };
  24890. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24891. var _this = this;
  24892. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24893. this._pickedDownMesh = pickResult.pickedMesh;
  24894. var actionManager = pickResult.pickedMesh.actionManager;
  24895. if (actionManager) {
  24896. if (actionManager.hasPickTriggers) {
  24897. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24898. switch (evt.button) {
  24899. case 0:
  24900. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24901. break;
  24902. case 1:
  24903. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24904. break;
  24905. case 2:
  24906. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24907. break;
  24908. }
  24909. }
  24910. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24911. window.setTimeout(function () {
  24912. 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);
  24913. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24914. if (_this._totalPointersPressed !== 0 &&
  24915. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24916. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24917. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24918. _this._startingPointerTime = 0;
  24919. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24920. }
  24921. }
  24922. }, Scene.LongPressDelay);
  24923. }
  24924. }
  24925. }
  24926. if (pickResult) {
  24927. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24928. if (this.onPointerDown) {
  24929. this.onPointerDown(evt, pickResult, type);
  24930. }
  24931. if (this.onPointerObservable.hasObservers()) {
  24932. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24933. this.onPointerObservable.notifyObservers(pi, type);
  24934. }
  24935. }
  24936. return this;
  24937. };
  24938. /**
  24939. * Use this method to simulate a pointer up 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.simulatePointerUp = function (pickResult, pointerEventInit) {
  24946. var evt = new PointerEvent("pointerup", pointerEventInit);
  24947. var clickInfo = new ClickInfo();
  24948. clickInfo.singleClick = true;
  24949. clickInfo.ignore = true;
  24950. return this._processPointerUp(pickResult, evt, clickInfo);
  24951. };
  24952. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24953. if (pickResult && pickResult && pickResult.pickedMesh) {
  24954. this._pickedUpMesh = pickResult.pickedMesh;
  24955. if (this._pickedDownMesh === this._pickedUpMesh) {
  24956. if (this.onPointerPick) {
  24957. this.onPointerPick(evt, pickResult);
  24958. }
  24959. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24960. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24961. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24962. this.onPointerObservable.notifyObservers(pi, type_1);
  24963. }
  24964. }
  24965. if (pickResult.pickedMesh.actionManager) {
  24966. if (clickInfo.ignore) {
  24967. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24968. }
  24969. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24970. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24971. }
  24972. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24973. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24974. }
  24975. }
  24976. }
  24977. if (this._pickedDownMesh &&
  24978. this._pickedDownMesh.actionManager &&
  24979. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24980. this._pickedDownMesh !== this._pickedUpMesh) {
  24981. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24982. }
  24983. var type = BABYLON.PointerEventTypes.POINTERUP;
  24984. if (this.onPointerObservable.hasObservers()) {
  24985. if (!clickInfo.ignore) {
  24986. if (!clickInfo.hasSwiped) {
  24987. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24988. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24989. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24990. this.onPointerObservable.notifyObservers(pi, type_2);
  24991. }
  24992. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24993. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24994. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24995. this.onPointerObservable.notifyObservers(pi, type_3);
  24996. }
  24997. }
  24998. }
  24999. else {
  25000. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25001. this.onPointerObservable.notifyObservers(pi, type);
  25002. }
  25003. }
  25004. if (this.onPointerUp) {
  25005. this.onPointerUp(evt, pickResult, type);
  25006. }
  25007. return this;
  25008. };
  25009. /**
  25010. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25011. * @param attachUp defines if you want to attach events to pointerup
  25012. * @param attachDown defines if you want to attach events to pointerdown
  25013. * @param attachMove defines if you want to attach events to pointermove
  25014. */
  25015. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25016. var _this = this;
  25017. if (attachUp === void 0) { attachUp = true; }
  25018. if (attachDown === void 0) { attachDown = true; }
  25019. if (attachMove === void 0) { attachMove = true; }
  25020. this._initActionManager = function (act, clickInfo) {
  25021. if (!_this._meshPickProceed) {
  25022. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25023. _this._currentPickResult = pickResult;
  25024. if (pickResult) {
  25025. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25026. }
  25027. _this._meshPickProceed = true;
  25028. }
  25029. return act;
  25030. };
  25031. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25032. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25033. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25034. btn !== _this._previousButtonPressed) {
  25035. _this._doubleClickOccured = false;
  25036. clickInfo.singleClick = true;
  25037. clickInfo.ignore = false;
  25038. cb(clickInfo, _this._currentPickResult);
  25039. }
  25040. };
  25041. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25042. var clickInfo = new ClickInfo();
  25043. _this._currentPickResult = null;
  25044. var act = null;
  25045. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25046. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25047. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25048. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25049. act = _this._initActionManager(act, clickInfo);
  25050. if (act)
  25051. checkPicking = act.hasPickTriggers;
  25052. }
  25053. if (checkPicking) {
  25054. var btn = evt.button;
  25055. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25056. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25057. if (!clickInfo.hasSwiped) {
  25058. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25059. if (!checkSingleClickImmediately) {
  25060. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25061. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25062. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25063. act = _this._initActionManager(act, clickInfo);
  25064. if (act)
  25065. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25066. }
  25067. }
  25068. if (checkSingleClickImmediately) {
  25069. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25070. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25071. btn !== _this._previousButtonPressed) {
  25072. clickInfo.singleClick = true;
  25073. cb(clickInfo, _this._currentPickResult);
  25074. }
  25075. }
  25076. // at least one double click is required to be check and exclusive double click is enabled
  25077. else {
  25078. // wait that no double click has been raised during the double click delay
  25079. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25080. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25081. }
  25082. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25083. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25084. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25085. act = _this._initActionManager(act, clickInfo);
  25086. if (act)
  25087. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25088. }
  25089. if (checkDoubleClick) {
  25090. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25091. if (btn === _this._previousButtonPressed &&
  25092. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25093. !_this._doubleClickOccured) {
  25094. // pointer has not moved for 2 clicks, it's a double click
  25095. if (!clickInfo.hasSwiped &&
  25096. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25097. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25098. _this._previousStartingPointerTime = 0;
  25099. _this._doubleClickOccured = true;
  25100. clickInfo.doubleClick = true;
  25101. clickInfo.ignore = false;
  25102. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25103. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25104. }
  25105. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25106. cb(clickInfo, _this._currentPickResult);
  25107. }
  25108. // if the two successive clicks are too far, it's just two simple clicks
  25109. else {
  25110. _this._doubleClickOccured = false;
  25111. _this._previousStartingPointerTime = _this._startingPointerTime;
  25112. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25113. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25114. _this._previousButtonPressed = btn;
  25115. if (Scene.ExclusiveDoubleClickMode) {
  25116. if (_this._previousDelayedSimpleClickTimeout) {
  25117. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25118. }
  25119. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25120. cb(clickInfo, _this._previousPickResult);
  25121. }
  25122. else {
  25123. cb(clickInfo, _this._currentPickResult);
  25124. }
  25125. }
  25126. }
  25127. // just the first click of the double has been raised
  25128. else {
  25129. _this._doubleClickOccured = false;
  25130. _this._previousStartingPointerTime = _this._startingPointerTime;
  25131. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25132. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25133. _this._previousButtonPressed = btn;
  25134. }
  25135. }
  25136. }
  25137. }
  25138. clickInfo.ignore = true;
  25139. cb(clickInfo, _this._currentPickResult);
  25140. };
  25141. this._spritePredicate = function (sprite) {
  25142. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25143. };
  25144. this._onPointerMove = function (evt) {
  25145. _this._updatePointerPosition(evt);
  25146. // PreObservable support
  25147. if (_this.onPrePointerObservable.hasObservers()) {
  25148. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25149. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25150. _this.onPrePointerObservable.notifyObservers(pi, type);
  25151. if (pi.skipOnPointerObservable) {
  25152. return;
  25153. }
  25154. }
  25155. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25156. return;
  25157. }
  25158. if (!_this.pointerMovePredicate) {
  25159. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25160. }
  25161. // Meshes
  25162. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25163. _this._processPointerMove(pickResult, evt);
  25164. };
  25165. this._onPointerDown = function (evt) {
  25166. _this._totalPointersPressed++;
  25167. _this._pickedDownMesh = null;
  25168. _this._meshPickProceed = false;
  25169. _this._updatePointerPosition(evt);
  25170. if (_this.preventDefaultOnPointerDown && canvas) {
  25171. evt.preventDefault();
  25172. canvas.focus();
  25173. }
  25174. // PreObservable support
  25175. if (_this.onPrePointerObservable.hasObservers()) {
  25176. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25177. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25178. _this.onPrePointerObservable.notifyObservers(pi, type);
  25179. if (pi.skipOnPointerObservable) {
  25180. return;
  25181. }
  25182. }
  25183. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25184. return;
  25185. }
  25186. _this._startingPointerPosition.x = _this._pointerX;
  25187. _this._startingPointerPosition.y = _this._pointerY;
  25188. _this._startingPointerTime = Date.now();
  25189. if (!_this.pointerDownPredicate) {
  25190. _this.pointerDownPredicate = function (mesh) {
  25191. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25192. };
  25193. }
  25194. // Meshes
  25195. _this._pickedDownMesh = null;
  25196. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25197. _this._processPointerDown(pickResult, evt);
  25198. // Sprites
  25199. _this._pickedDownSprite = null;
  25200. if (_this.spriteManagers.length > 0) {
  25201. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25202. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25203. if (pickResult.pickedSprite.actionManager) {
  25204. _this._pickedDownSprite = pickResult.pickedSprite;
  25205. switch (evt.button) {
  25206. case 0:
  25207. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25208. break;
  25209. case 1:
  25210. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25211. break;
  25212. case 2:
  25213. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25214. break;
  25215. }
  25216. if (pickResult.pickedSprite.actionManager) {
  25217. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25218. }
  25219. }
  25220. }
  25221. }
  25222. };
  25223. this._onPointerUp = function (evt) {
  25224. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25225. return; // So we need to test it the pointer down was pressed before.
  25226. }
  25227. _this._totalPointersPressed--;
  25228. _this._pickedUpMesh = null;
  25229. _this._meshPickProceed = false;
  25230. _this._updatePointerPosition(evt);
  25231. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25232. // PreObservable support
  25233. if (_this.onPrePointerObservable.hasObservers()) {
  25234. if (!clickInfo.ignore) {
  25235. if (!clickInfo.hasSwiped) {
  25236. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25237. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25238. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25239. _this.onPrePointerObservable.notifyObservers(pi, type);
  25240. if (pi.skipOnPointerObservable) {
  25241. return;
  25242. }
  25243. }
  25244. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25245. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25246. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25247. _this.onPrePointerObservable.notifyObservers(pi, type);
  25248. if (pi.skipOnPointerObservable) {
  25249. return;
  25250. }
  25251. }
  25252. }
  25253. }
  25254. else {
  25255. var type = BABYLON.PointerEventTypes.POINTERUP;
  25256. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25257. _this.onPrePointerObservable.notifyObservers(pi, type);
  25258. if (pi.skipOnPointerObservable) {
  25259. return;
  25260. }
  25261. }
  25262. }
  25263. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25264. return;
  25265. }
  25266. if (!_this.pointerUpPredicate) {
  25267. _this.pointerUpPredicate = function (mesh) {
  25268. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25269. };
  25270. }
  25271. // Meshes
  25272. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25273. _this._initActionManager(null, clickInfo);
  25274. }
  25275. if (!pickResult) {
  25276. pickResult = _this._currentPickResult;
  25277. }
  25278. _this._processPointerUp(pickResult, evt, clickInfo);
  25279. // Sprites
  25280. if (!clickInfo.ignore) {
  25281. if (_this.spriteManagers.length > 0) {
  25282. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25283. if (spritePickResult) {
  25284. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25285. if (spritePickResult.pickedSprite.actionManager) {
  25286. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25287. if (spritePickResult.pickedSprite.actionManager) {
  25288. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25289. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25290. }
  25291. }
  25292. }
  25293. }
  25294. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25295. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25296. }
  25297. }
  25298. }
  25299. }
  25300. _this._previousPickResult = _this._currentPickResult;
  25301. });
  25302. };
  25303. this._onKeyDown = function (evt) {
  25304. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25305. if (_this.onPreKeyboardObservable.hasObservers()) {
  25306. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25307. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25308. if (pi.skipOnPointerObservable) {
  25309. return;
  25310. }
  25311. }
  25312. if (_this.onKeyboardObservable.hasObservers()) {
  25313. var pi = new BABYLON.KeyboardInfo(type, evt);
  25314. _this.onKeyboardObservable.notifyObservers(pi, type);
  25315. }
  25316. if (_this.actionManager) {
  25317. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25318. }
  25319. };
  25320. this._onKeyUp = function (evt) {
  25321. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25322. if (_this.onPreKeyboardObservable.hasObservers()) {
  25323. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25324. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25325. if (pi.skipOnPointerObservable) {
  25326. return;
  25327. }
  25328. }
  25329. if (_this.onKeyboardObservable.hasObservers()) {
  25330. var pi = new BABYLON.KeyboardInfo(type, evt);
  25331. _this.onKeyboardObservable.notifyObservers(pi, type);
  25332. }
  25333. if (_this.actionManager) {
  25334. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25335. }
  25336. };
  25337. var engine = this.getEngine();
  25338. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25339. if (!canvas) {
  25340. return;
  25341. }
  25342. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25343. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25344. });
  25345. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25346. if (!canvas) {
  25347. return;
  25348. }
  25349. canvas.removeEventListener("keydown", _this._onKeyDown);
  25350. canvas.removeEventListener("keyup", _this._onKeyUp);
  25351. });
  25352. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25353. var canvas = this._engine.getRenderingCanvas();
  25354. if (!canvas) {
  25355. return;
  25356. }
  25357. if (attachMove) {
  25358. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25359. // Wheel
  25360. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25361. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25362. }
  25363. if (attachDown) {
  25364. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25365. }
  25366. if (attachUp) {
  25367. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25368. }
  25369. canvas.tabIndex = 1;
  25370. };
  25371. /** Detaches all event handlers*/
  25372. Scene.prototype.detachControl = function () {
  25373. var engine = this.getEngine();
  25374. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25375. var canvas = engine.getRenderingCanvas();
  25376. if (!canvas) {
  25377. return;
  25378. }
  25379. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25380. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25381. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25382. if (this._onCanvasBlurObserver) {
  25383. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25384. }
  25385. if (this._onCanvasFocusObserver) {
  25386. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25387. }
  25388. // Wheel
  25389. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25390. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25391. // Keyboard
  25392. canvas.removeEventListener("keydown", this._onKeyDown);
  25393. canvas.removeEventListener("keyup", this._onKeyUp);
  25394. // Observables
  25395. this.onKeyboardObservable.clear();
  25396. this.onPreKeyboardObservable.clear();
  25397. this.onPointerObservable.clear();
  25398. this.onPrePointerObservable.clear();
  25399. };
  25400. /**
  25401. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25402. * Delay loaded resources are not taking in account
  25403. * @return true if all required resources are ready
  25404. */
  25405. Scene.prototype.isReady = function () {
  25406. if (this._isDisposed) {
  25407. return false;
  25408. }
  25409. if (this._pendingData.length > 0) {
  25410. return false;
  25411. }
  25412. var index;
  25413. var engine = this.getEngine();
  25414. // Geometries
  25415. for (index = 0; index < this._geometries.length; index++) {
  25416. var geometry = this._geometries[index];
  25417. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25418. return false;
  25419. }
  25420. }
  25421. // Meshes
  25422. for (index = 0; index < this.meshes.length; index++) {
  25423. var mesh = this.meshes[index];
  25424. if (!mesh.isEnabled()) {
  25425. continue;
  25426. }
  25427. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25428. continue;
  25429. }
  25430. if (!mesh.isReady(true)) {
  25431. return false;
  25432. }
  25433. // Effect layers
  25434. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25435. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25436. var layer = _a[_i];
  25437. if (!layer.hasMesh(mesh)) {
  25438. continue;
  25439. }
  25440. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25441. var subMesh = _c[_b];
  25442. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25443. return false;
  25444. }
  25445. }
  25446. }
  25447. }
  25448. // Post-processes
  25449. if (this.activeCameras && this.activeCameras.length > 0) {
  25450. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25451. var camera = _e[_d];
  25452. if (!camera.isReady(true)) {
  25453. return false;
  25454. }
  25455. }
  25456. }
  25457. else if (this.activeCamera) {
  25458. if (!this.activeCamera.isReady(true)) {
  25459. return false;
  25460. }
  25461. }
  25462. // Particles
  25463. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25464. var particleSystem = _g[_f];
  25465. if (!particleSystem.isReady()) {
  25466. return false;
  25467. }
  25468. }
  25469. return true;
  25470. };
  25471. /** Resets all cached information relative to material (including effect and visibility) */
  25472. Scene.prototype.resetCachedMaterial = function () {
  25473. this._cachedMaterial = null;
  25474. this._cachedEffect = null;
  25475. this._cachedVisibility = null;
  25476. };
  25477. /**
  25478. * Registers a function to be called before every frame render
  25479. * @param func defines the function to register
  25480. */
  25481. Scene.prototype.registerBeforeRender = function (func) {
  25482. this.onBeforeRenderObservable.add(func);
  25483. };
  25484. /**
  25485. * Unregisters a function called before every frame render
  25486. * @param func defines the function to unregister
  25487. */
  25488. Scene.prototype.unregisterBeforeRender = function (func) {
  25489. this.onBeforeRenderObservable.removeCallback(func);
  25490. };
  25491. /**
  25492. * Registers a function to be called after every frame render
  25493. * @param func defines the function to register
  25494. */
  25495. Scene.prototype.registerAfterRender = function (func) {
  25496. this.onAfterRenderObservable.add(func);
  25497. };
  25498. /**
  25499. * Unregisters a function called after every frame render
  25500. * @param func defines the function to unregister
  25501. */
  25502. Scene.prototype.unregisterAfterRender = function (func) {
  25503. this.onAfterRenderObservable.removeCallback(func);
  25504. };
  25505. Scene.prototype._executeOnceBeforeRender = function (func) {
  25506. var _this = this;
  25507. var execFunc = function () {
  25508. func();
  25509. setTimeout(function () {
  25510. _this.unregisterBeforeRender(execFunc);
  25511. });
  25512. };
  25513. this.registerBeforeRender(execFunc);
  25514. };
  25515. /**
  25516. * The provided function will run before render once and will be disposed afterwards.
  25517. * A timeout delay can be provided so that the function will be executed in N ms.
  25518. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25519. * @param func The function to be executed.
  25520. * @param timeout optional delay in ms
  25521. */
  25522. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25523. var _this = this;
  25524. if (timeout !== undefined) {
  25525. setTimeout(function () {
  25526. _this._executeOnceBeforeRender(func);
  25527. }, timeout);
  25528. }
  25529. else {
  25530. this._executeOnceBeforeRender(func);
  25531. }
  25532. };
  25533. /** @hidden */
  25534. Scene.prototype._addPendingData = function (data) {
  25535. this._pendingData.push(data);
  25536. };
  25537. /** @hidden */
  25538. Scene.prototype._removePendingData = function (data) {
  25539. var wasLoading = this.isLoading;
  25540. var index = this._pendingData.indexOf(data);
  25541. if (index !== -1) {
  25542. this._pendingData.splice(index, 1);
  25543. }
  25544. if (wasLoading && !this.isLoading) {
  25545. this.onDataLoadedObservable.notifyObservers(this);
  25546. }
  25547. };
  25548. /**
  25549. * Returns the number of items waiting to be loaded
  25550. * @returns the number of items waiting to be loaded
  25551. */
  25552. Scene.prototype.getWaitingItemsCount = function () {
  25553. return this._pendingData.length;
  25554. };
  25555. Object.defineProperty(Scene.prototype, "isLoading", {
  25556. /**
  25557. * Returns a boolean indicating if the scene is still loading data
  25558. */
  25559. get: function () {
  25560. return this._pendingData.length > 0;
  25561. },
  25562. enumerable: true,
  25563. configurable: true
  25564. });
  25565. /**
  25566. * Registers a function to be executed when the scene is ready
  25567. * @param {Function} func - the function to be executed
  25568. */
  25569. Scene.prototype.executeWhenReady = function (func) {
  25570. var _this = this;
  25571. this.onReadyObservable.add(func);
  25572. if (this._executeWhenReadyTimeoutId !== -1) {
  25573. return;
  25574. }
  25575. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25576. _this._checkIsReady();
  25577. }, 150);
  25578. };
  25579. /**
  25580. * Returns a promise that resolves when the scene is ready
  25581. * @returns A promise that resolves when the scene is ready
  25582. */
  25583. Scene.prototype.whenReadyAsync = function () {
  25584. var _this = this;
  25585. return new Promise(function (resolve) {
  25586. _this.executeWhenReady(function () {
  25587. resolve();
  25588. });
  25589. });
  25590. };
  25591. /** @hidden */
  25592. Scene.prototype._checkIsReady = function () {
  25593. var _this = this;
  25594. if (this.isReady()) {
  25595. this.onReadyObservable.notifyObservers(this);
  25596. this.onReadyObservable.clear();
  25597. this._executeWhenReadyTimeoutId = -1;
  25598. return;
  25599. }
  25600. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25601. _this._checkIsReady();
  25602. }, 150);
  25603. };
  25604. // Animations
  25605. /**
  25606. * Will start the animation sequence of a given target
  25607. * @param target defines the target
  25608. * @param from defines from which frame should animation start
  25609. * @param to defines until which frame should animation run.
  25610. * @param weight defines the weight to apply to the animation (1.0 by default)
  25611. * @param loop defines if the animation loops
  25612. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25613. * @param onAnimationEnd defines the function to be executed when the animation ends
  25614. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25615. * @returns the animatable object created for this animation
  25616. */
  25617. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25618. if (weight === void 0) { weight = 1.0; }
  25619. if (speedRatio === void 0) { speedRatio = 1.0; }
  25620. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25621. returnedAnimatable.weight = weight;
  25622. return returnedAnimatable;
  25623. };
  25624. /**
  25625. * Will start the animation sequence of a given target
  25626. * @param target defines the target
  25627. * @param from defines from which frame should animation start
  25628. * @param to defines until which frame should animation run.
  25629. * @param loop defines if the animation loops
  25630. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25631. * @param onAnimationEnd defines the function to be executed when the animation ends
  25632. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25633. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25634. * @returns the animatable object created for this animation
  25635. */
  25636. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25637. if (speedRatio === void 0) { speedRatio = 1.0; }
  25638. if (stopCurrent === void 0) { stopCurrent = true; }
  25639. if (from > to && speedRatio > 0) {
  25640. speedRatio *= -1;
  25641. }
  25642. if (stopCurrent) {
  25643. this.stopAnimation(target);
  25644. }
  25645. if (!animatable) {
  25646. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25647. }
  25648. // Local animations
  25649. if (target.animations) {
  25650. animatable.appendAnimations(target, target.animations);
  25651. }
  25652. // Children animations
  25653. if (target.getAnimatables) {
  25654. var animatables = target.getAnimatables();
  25655. for (var index = 0; index < animatables.length; index++) {
  25656. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25657. }
  25658. }
  25659. animatable.reset();
  25660. return animatable;
  25661. };
  25662. /**
  25663. * Begin a new animation on a given node
  25664. * @param target defines the target where the animation will take place
  25665. * @param animations defines the list of animations to start
  25666. * @param from defines the initial value
  25667. * @param to defines the final value
  25668. * @param loop defines if you want animation to loop (off by default)
  25669. * @param speedRatio defines the speed ratio to apply to all animations
  25670. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25671. * @returns the list of created animatables
  25672. */
  25673. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25674. if (speedRatio === undefined) {
  25675. speedRatio = 1.0;
  25676. }
  25677. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25678. return animatable;
  25679. };
  25680. /**
  25681. * Begin a new animation on a given node and its hierarchy
  25682. * @param target defines the root node where the animation will take place
  25683. * @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.
  25684. * @param animations defines the list of animations to start
  25685. * @param from defines the initial value
  25686. * @param to defines the final value
  25687. * @param loop defines if you want animation to loop (off by default)
  25688. * @param speedRatio defines the speed ratio to apply to all animations
  25689. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25690. * @returns the list of animatables created for all nodes
  25691. */
  25692. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25693. var children = target.getDescendants(directDescendantsOnly);
  25694. var result = [];
  25695. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25696. var child = children_1[_i];
  25697. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25698. }
  25699. return result;
  25700. };
  25701. /**
  25702. * Gets the animatable associated with a specific target
  25703. * @param target defines the target of the animatable
  25704. * @returns the required animatable if found
  25705. */
  25706. Scene.prototype.getAnimatableByTarget = function (target) {
  25707. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25708. if (this._activeAnimatables[index].target === target) {
  25709. return this._activeAnimatables[index];
  25710. }
  25711. }
  25712. return null;
  25713. };
  25714. /**
  25715. * Gets all animatables associated with a given target
  25716. * @param target defines the target to look animatables for
  25717. * @returns an array of Animatables
  25718. */
  25719. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25720. var result = [];
  25721. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25722. if (this._activeAnimatables[index].target === target) {
  25723. result.push(this._activeAnimatables[index]);
  25724. }
  25725. }
  25726. return result;
  25727. };
  25728. Object.defineProperty(Scene.prototype, "animatables", {
  25729. /**
  25730. * Gets all animatable attached to the scene
  25731. */
  25732. get: function () {
  25733. return this._activeAnimatables;
  25734. },
  25735. enumerable: true,
  25736. configurable: true
  25737. });
  25738. /**
  25739. * Will stop the animation of the given target
  25740. * @param target - the target
  25741. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25742. */
  25743. Scene.prototype.stopAnimation = function (target, animationName) {
  25744. var animatables = this.getAllAnimatablesByTarget(target);
  25745. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25746. var animatable = animatables_1[_i];
  25747. animatable.stop(animationName);
  25748. }
  25749. };
  25750. /**
  25751. * Stops and removes all animations that have been applied to the scene
  25752. */
  25753. Scene.prototype.stopAllAnimations = function () {
  25754. if (this._activeAnimatables) {
  25755. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25756. this._activeAnimatables[i].stop();
  25757. }
  25758. this._activeAnimatables = [];
  25759. }
  25760. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25761. var group = _a[_i];
  25762. group.stop();
  25763. }
  25764. };
  25765. Scene.prototype._animate = function () {
  25766. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25767. return;
  25768. }
  25769. // Getting time
  25770. var now = BABYLON.Tools.Now;
  25771. if (!this._animationTimeLast) {
  25772. if (this._pendingData.length > 0) {
  25773. return;
  25774. }
  25775. this._animationTimeLast = now;
  25776. }
  25777. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25778. this._animationTime += deltaTime;
  25779. this._animationTimeLast = now;
  25780. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25781. this._activeAnimatables[index]._animate(this._animationTime);
  25782. }
  25783. // Late animation bindings
  25784. this._processLateAnimationBindings();
  25785. };
  25786. /** @hidden */
  25787. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25788. var target = runtimeAnimation.target;
  25789. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25790. if (!target._lateAnimationHolders) {
  25791. target._lateAnimationHolders = {};
  25792. }
  25793. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25794. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25795. totalWeight: 0,
  25796. animations: []
  25797. };
  25798. }
  25799. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25800. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25801. };
  25802. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25803. var normalizer = 1.0;
  25804. var finalPosition = BABYLON.Tmp.Vector3[0];
  25805. var finalScaling = BABYLON.Tmp.Vector3[1];
  25806. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25807. var startIndex = 0;
  25808. var originalAnimation = holder.animations[0];
  25809. var scale = 1;
  25810. if (holder.totalWeight < 1.0) {
  25811. // We need to mix the original value in
  25812. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25813. scale = 1.0 - holder.totalWeight;
  25814. }
  25815. else {
  25816. startIndex = 1;
  25817. // We need to normalize the weights
  25818. normalizer = holder.totalWeight;
  25819. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25820. scale = originalAnimation.weight / normalizer;
  25821. if (scale == 1) {
  25822. return originalAnimation.currentValue;
  25823. }
  25824. }
  25825. finalScaling.scaleInPlace(scale);
  25826. finalPosition.scaleInPlace(scale);
  25827. finalQuaternion.scaleInPlace(scale);
  25828. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25829. var runtimeAnimation = holder.animations[animIndex];
  25830. var scale = runtimeAnimation.weight / normalizer;
  25831. var currentPosition = BABYLON.Tmp.Vector3[2];
  25832. var currentScaling = BABYLON.Tmp.Vector3[3];
  25833. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25834. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25835. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25836. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25837. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25838. }
  25839. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25840. return originalAnimation._workValue;
  25841. };
  25842. Scene.prototype._processLateAnimationBindings = function () {
  25843. if (!this._registeredForLateAnimationBindings.length) {
  25844. return;
  25845. }
  25846. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25847. var target = this._registeredForLateAnimationBindings.data[index];
  25848. for (var path in target._lateAnimationHolders) {
  25849. var holder = target._lateAnimationHolders[path];
  25850. var originalAnimation = holder.animations[0];
  25851. var originalValue = originalAnimation.originalValue;
  25852. var finalTarget = originalAnimation.target;
  25853. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25854. var finalValue = void 0;
  25855. if (matrixDecomposeMode) {
  25856. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25857. }
  25858. else {
  25859. var startIndex = 0;
  25860. var normalizer = 1.0;
  25861. if (holder.totalWeight < 1.0) {
  25862. // We need to mix the original value in
  25863. if (originalValue.scale) {
  25864. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25865. }
  25866. else {
  25867. finalValue = originalValue * (1.0 - holder.totalWeight);
  25868. }
  25869. }
  25870. else {
  25871. // We need to normalize the weights
  25872. normalizer = holder.totalWeight;
  25873. var scale_1 = originalAnimation.weight / normalizer;
  25874. if (scale_1 !== 1) {
  25875. if (originalAnimation.currentValue.scale) {
  25876. finalValue = originalAnimation.currentValue.scale(scale_1);
  25877. }
  25878. else {
  25879. finalValue = originalAnimation.currentValue * scale_1;
  25880. }
  25881. }
  25882. else {
  25883. finalValue = originalAnimation.currentValue;
  25884. }
  25885. startIndex = 1;
  25886. }
  25887. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25888. var runtimeAnimation = holder.animations[animIndex];
  25889. var scale = runtimeAnimation.weight / normalizer;
  25890. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25891. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25892. }
  25893. else {
  25894. finalValue += runtimeAnimation.currentValue * scale;
  25895. }
  25896. }
  25897. }
  25898. finalTarget[path] = finalValue;
  25899. }
  25900. target._lateAnimationHolders = {};
  25901. }
  25902. this._registeredForLateAnimationBindings.reset();
  25903. };
  25904. // Matrix
  25905. /** @hidden */
  25906. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25907. this._useAlternateCameraConfiguration = active;
  25908. };
  25909. /**
  25910. * Gets the current view matrix
  25911. * @returns a Matrix
  25912. */
  25913. Scene.prototype.getViewMatrix = function () {
  25914. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25915. };
  25916. /**
  25917. * Gets the current projection matrix
  25918. * @returns a Matrix
  25919. */
  25920. Scene.prototype.getProjectionMatrix = function () {
  25921. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25922. };
  25923. /**
  25924. * Gets the current transform matrix
  25925. * @returns a Matrix made of View * Projection
  25926. */
  25927. Scene.prototype.getTransformMatrix = function () {
  25928. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25929. };
  25930. /**
  25931. * Sets the current transform matrix
  25932. * @param view defines the View matrix to use
  25933. * @param projection defines the Projection matrix to use
  25934. */
  25935. Scene.prototype.setTransformMatrix = function (view, projection) {
  25936. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25937. return;
  25938. }
  25939. this._viewUpdateFlag = view.updateFlag;
  25940. this._projectionUpdateFlag = projection.updateFlag;
  25941. this._viewMatrix = view;
  25942. this._projectionMatrix = projection;
  25943. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25944. // Update frustum
  25945. if (!this._frustumPlanes) {
  25946. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25947. }
  25948. else {
  25949. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25950. }
  25951. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25952. var otherCamera = this.activeCamera._alternateCamera;
  25953. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25954. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25955. }
  25956. if (this._sceneUbo.useUbo) {
  25957. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25958. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25959. this._sceneUbo.update();
  25960. }
  25961. };
  25962. /** @hidden */
  25963. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25964. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25965. return;
  25966. }
  25967. this._alternateViewUpdateFlag = view.updateFlag;
  25968. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25969. this._alternateViewMatrix = view;
  25970. this._alternateProjectionMatrix = projection;
  25971. if (!this._alternateTransformMatrix) {
  25972. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25973. }
  25974. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25975. if (!this._alternateSceneUbo) {
  25976. this._createAlternateUbo();
  25977. }
  25978. if (this._alternateSceneUbo.useUbo) {
  25979. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25980. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25981. this._alternateSceneUbo.update();
  25982. }
  25983. };
  25984. /**
  25985. * Gets the uniform buffer used to store scene data
  25986. * @returns a UniformBuffer
  25987. */
  25988. Scene.prototype.getSceneUniformBuffer = function () {
  25989. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25990. };
  25991. /**
  25992. * Gets an unique (relatively to the current scene) Id
  25993. * @returns an unique number for the scene
  25994. */
  25995. Scene.prototype.getUniqueId = function () {
  25996. var result = Scene._uniqueIdCounter;
  25997. Scene._uniqueIdCounter++;
  25998. return result;
  25999. };
  26000. /**
  26001. * Add a mesh to the list of scene's meshes
  26002. * @param newMesh defines the mesh to add
  26003. */
  26004. Scene.prototype.addMesh = function (newMesh) {
  26005. this.meshes.push(newMesh);
  26006. //notify the collision coordinator
  26007. if (this.collisionCoordinator) {
  26008. this.collisionCoordinator.onMeshAdded(newMesh);
  26009. }
  26010. newMesh._resyncLightSources();
  26011. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26012. };
  26013. /**
  26014. * Remove a mesh for the list of scene's meshes
  26015. * @param toRemove defines the mesh to remove
  26016. * @param recursive if all child meshes should also be removed from the scene
  26017. * @returns the index where the mesh was in the mesh list
  26018. */
  26019. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26020. var _this = this;
  26021. if (recursive === void 0) { recursive = false; }
  26022. var index = this.meshes.indexOf(toRemove);
  26023. if (index !== -1) {
  26024. // Remove from the scene if mesh found
  26025. this.meshes.splice(index, 1);
  26026. }
  26027. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26028. if (recursive) {
  26029. toRemove.getChildMeshes().forEach(function (m) {
  26030. _this.removeMesh(m);
  26031. });
  26032. }
  26033. return index;
  26034. };
  26035. /**
  26036. * Add a transform node to the list of scene's transform nodes
  26037. * @param newTransformNode defines the transform node to add
  26038. */
  26039. Scene.prototype.addTransformNode = function (newTransformNode) {
  26040. this.transformNodes.push(newTransformNode);
  26041. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26042. };
  26043. /**
  26044. * Remove a transform node for the list of scene's transform nodes
  26045. * @param toRemove defines the transform node to remove
  26046. * @returns the index where the transform node was in the transform node list
  26047. */
  26048. Scene.prototype.removeTransformNode = function (toRemove) {
  26049. var index = this.transformNodes.indexOf(toRemove);
  26050. if (index !== -1) {
  26051. // Remove from the scene if found
  26052. this.transformNodes.splice(index, 1);
  26053. }
  26054. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26055. return index;
  26056. };
  26057. /**
  26058. * Remove a skeleton for the list of scene's skeletons
  26059. * @param toRemove defines the skeleton to remove
  26060. * @returns the index where the skeleton was in the skeleton list
  26061. */
  26062. Scene.prototype.removeSkeleton = function (toRemove) {
  26063. var index = this.skeletons.indexOf(toRemove);
  26064. if (index !== -1) {
  26065. // Remove from the scene if found
  26066. this.skeletons.splice(index, 1);
  26067. }
  26068. return index;
  26069. };
  26070. /**
  26071. * Remove a morph target for the list of scene's morph targets
  26072. * @param toRemove defines the morph target to remove
  26073. * @returns the index where the morph target was in the morph target list
  26074. */
  26075. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26076. var index = this.morphTargetManagers.indexOf(toRemove);
  26077. if (index !== -1) {
  26078. // Remove from the scene if found
  26079. this.morphTargetManagers.splice(index, 1);
  26080. }
  26081. return index;
  26082. };
  26083. /**
  26084. * Remove a light for the list of scene's lights
  26085. * @param toRemove defines the light to remove
  26086. * @returns the index where the light was in the light list
  26087. */
  26088. Scene.prototype.removeLight = function (toRemove) {
  26089. var index = this.lights.indexOf(toRemove);
  26090. if (index !== -1) {
  26091. // Remove from meshes
  26092. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26093. var mesh = _a[_i];
  26094. mesh._removeLightSource(toRemove);
  26095. }
  26096. // Remove from the scene if mesh found
  26097. this.lights.splice(index, 1);
  26098. this.sortLightsByPriority();
  26099. }
  26100. this.onLightRemovedObservable.notifyObservers(toRemove);
  26101. return index;
  26102. };
  26103. /**
  26104. * Remove a camera for the list of scene's cameras
  26105. * @param toRemove defines the camera to remove
  26106. * @returns the index where the camera was in the camera list
  26107. */
  26108. Scene.prototype.removeCamera = function (toRemove) {
  26109. var index = this.cameras.indexOf(toRemove);
  26110. if (index !== -1) {
  26111. // Remove from the scene if mesh found
  26112. this.cameras.splice(index, 1);
  26113. }
  26114. // Remove from activeCameras
  26115. var index2 = this.activeCameras.indexOf(toRemove);
  26116. if (index2 !== -1) {
  26117. // Remove from the scene if mesh found
  26118. this.activeCameras.splice(index2, 1);
  26119. }
  26120. // Reset the activeCamera
  26121. if (this.activeCamera === toRemove) {
  26122. if (this.cameras.length > 0) {
  26123. this.activeCamera = this.cameras[0];
  26124. }
  26125. else {
  26126. this.activeCamera = null;
  26127. }
  26128. }
  26129. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26130. return index;
  26131. };
  26132. /**
  26133. * Remove a particle system for the list of scene's particle systems
  26134. * @param toRemove defines the particle system to remove
  26135. * @returns the index where the particle system was in the particle system list
  26136. */
  26137. Scene.prototype.removeParticleSystem = function (toRemove) {
  26138. var index = this.particleSystems.indexOf(toRemove);
  26139. if (index !== -1) {
  26140. this.particleSystems.splice(index, 1);
  26141. }
  26142. return index;
  26143. };
  26144. /**
  26145. * Remove a animation for the list of scene's animations
  26146. * @param toRemove defines the animation to remove
  26147. * @returns the index where the animation was in the animation list
  26148. */
  26149. Scene.prototype.removeAnimation = function (toRemove) {
  26150. var index = this.animations.indexOf(toRemove);
  26151. if (index !== -1) {
  26152. this.animations.splice(index, 1);
  26153. }
  26154. return index;
  26155. };
  26156. /**
  26157. * Removes the given animation group from this scene.
  26158. * @param toRemove The animation group to remove
  26159. * @returns The index of the removed animation group
  26160. */
  26161. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26162. var index = this.animationGroups.indexOf(toRemove);
  26163. if (index !== -1) {
  26164. this.animationGroups.splice(index, 1);
  26165. }
  26166. return index;
  26167. };
  26168. /**
  26169. * Removes the given multi-material from this scene.
  26170. * @param toRemove The multi-material to remove
  26171. * @returns The index of the removed multi-material
  26172. */
  26173. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26174. var index = this.multiMaterials.indexOf(toRemove);
  26175. if (index !== -1) {
  26176. this.multiMaterials.splice(index, 1);
  26177. }
  26178. return index;
  26179. };
  26180. /**
  26181. * Removes the given material from this scene.
  26182. * @param toRemove The material to remove
  26183. * @returns The index of the removed material
  26184. */
  26185. Scene.prototype.removeMaterial = function (toRemove) {
  26186. var index = this.materials.indexOf(toRemove);
  26187. if (index !== -1) {
  26188. this.materials.splice(index, 1);
  26189. }
  26190. return index;
  26191. };
  26192. /**
  26193. * Removes the given lens flare system from this scene.
  26194. * @param toRemove The lens flare system to remove
  26195. * @returns The index of the removed lens flare system
  26196. */
  26197. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26198. var index = this.lensFlareSystems.indexOf(toRemove);
  26199. if (index !== -1) {
  26200. this.lensFlareSystems.splice(index, 1);
  26201. }
  26202. return index;
  26203. };
  26204. /**
  26205. * Removes the given action manager from this scene.
  26206. * @param toRemove The action manager to remove
  26207. * @returns The index of the removed action manager
  26208. */
  26209. Scene.prototype.removeActionManager = function (toRemove) {
  26210. var index = this._actionManagers.indexOf(toRemove);
  26211. if (index !== -1) {
  26212. this._actionManagers.splice(index, 1);
  26213. }
  26214. return index;
  26215. };
  26216. /**
  26217. * Removes the given effect layer from this scene.
  26218. * @param toRemove defines the effect layer to remove
  26219. * @returns the index of the removed effect layer
  26220. */
  26221. Scene.prototype.removeEffectLayer = function (toRemove) {
  26222. var index = this.effectLayers.indexOf(toRemove);
  26223. if (index !== -1) {
  26224. this.effectLayers.splice(index, 1);
  26225. }
  26226. return index;
  26227. };
  26228. /**
  26229. * Removes the given texture from this scene.
  26230. * @param toRemove The texture to remove
  26231. * @returns The index of the removed texture
  26232. */
  26233. Scene.prototype.removeTexture = function (toRemove) {
  26234. var index = this.textures.indexOf(toRemove);
  26235. if (index !== -1) {
  26236. this.textures.splice(index, 1);
  26237. }
  26238. return index;
  26239. };
  26240. /**
  26241. * Adds the given light to this scene
  26242. * @param newLight The light to add
  26243. */
  26244. Scene.prototype.addLight = function (newLight) {
  26245. this.lights.push(newLight);
  26246. this.sortLightsByPriority();
  26247. // Add light to all meshes (To support if the light is removed and then readded)
  26248. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26249. var mesh = _a[_i];
  26250. if (mesh._lightSources.indexOf(newLight) === -1) {
  26251. mesh._lightSources.push(newLight);
  26252. mesh._resyncLightSources();
  26253. }
  26254. }
  26255. this.onNewLightAddedObservable.notifyObservers(newLight);
  26256. };
  26257. /**
  26258. * Sorts the list list based on light priorities
  26259. */
  26260. Scene.prototype.sortLightsByPriority = function () {
  26261. if (this.requireLightSorting) {
  26262. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26263. }
  26264. };
  26265. /**
  26266. * Adds the given camera to this scene
  26267. * @param newCamera The camera to add
  26268. */
  26269. Scene.prototype.addCamera = function (newCamera) {
  26270. this.cameras.push(newCamera);
  26271. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26272. };
  26273. /**
  26274. * Adds the given skeleton to this scene
  26275. * @param newSkeleton The skeleton to add
  26276. */
  26277. Scene.prototype.addSkeleton = function (newSkeleton) {
  26278. this.skeletons.push(newSkeleton);
  26279. };
  26280. /**
  26281. * Adds the given particle system to this scene
  26282. * @param newParticleSystem The particle system to add
  26283. */
  26284. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26285. this.particleSystems.push(newParticleSystem);
  26286. };
  26287. /**
  26288. * Adds the given animation to this scene
  26289. * @param newAnimation The animation to add
  26290. */
  26291. Scene.prototype.addAnimation = function (newAnimation) {
  26292. this.animations.push(newAnimation);
  26293. };
  26294. /**
  26295. * Adds the given animation group to this scene.
  26296. * @param newAnimationGroup The animation group to add
  26297. */
  26298. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26299. this.animationGroups.push(newAnimationGroup);
  26300. };
  26301. /**
  26302. * Adds the given multi-material to this scene
  26303. * @param newMultiMaterial The multi-material to add
  26304. */
  26305. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26306. this.multiMaterials.push(newMultiMaterial);
  26307. };
  26308. /**
  26309. * Adds the given material to this scene
  26310. * @param newMaterial The material to add
  26311. */
  26312. Scene.prototype.addMaterial = function (newMaterial) {
  26313. this.materials.push(newMaterial);
  26314. };
  26315. /**
  26316. * Adds the given morph target to this scene
  26317. * @param newMorphTargetManager The morph target to add
  26318. */
  26319. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26320. this.morphTargetManagers.push(newMorphTargetManager);
  26321. };
  26322. /**
  26323. * Adds the given geometry to this scene
  26324. * @param newGeometry The geometry to add
  26325. */
  26326. Scene.prototype.addGeometry = function (newGeometry) {
  26327. this._geometries.push(newGeometry);
  26328. };
  26329. /**
  26330. * Adds the given lens flare system to this scene
  26331. * @param newLensFlareSystem The lens flare system to add
  26332. */
  26333. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26334. this.lensFlareSystems.push(newLensFlareSystem);
  26335. };
  26336. /**
  26337. * Adds the given effect layer to this scene
  26338. * @param newEffectLayer defines the effect layer to add
  26339. */
  26340. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26341. this.effectLayers.push(newEffectLayer);
  26342. };
  26343. /**
  26344. * Adds the given action manager to this scene
  26345. * @param newActionManager The action manager to add
  26346. */
  26347. Scene.prototype.addActionManager = function (newActionManager) {
  26348. this._actionManagers.push(newActionManager);
  26349. };
  26350. /**
  26351. * Adds the given texture to this scene.
  26352. * @param newTexture The texture to add
  26353. */
  26354. Scene.prototype.addTexture = function (newTexture) {
  26355. this.textures.push(newTexture);
  26356. };
  26357. /**
  26358. * Switch active camera
  26359. * @param newCamera defines the new active camera
  26360. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26361. */
  26362. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26363. if (attachControl === void 0) { attachControl = true; }
  26364. var canvas = this._engine.getRenderingCanvas();
  26365. if (!canvas) {
  26366. return;
  26367. }
  26368. if (this.activeCamera) {
  26369. this.activeCamera.detachControl(canvas);
  26370. }
  26371. this.activeCamera = newCamera;
  26372. if (attachControl) {
  26373. newCamera.attachControl(canvas);
  26374. }
  26375. };
  26376. /**
  26377. * sets the active camera of the scene using its ID
  26378. * @param id defines the camera's ID
  26379. * @return the new active camera or null if none found.
  26380. */
  26381. Scene.prototype.setActiveCameraByID = function (id) {
  26382. var camera = this.getCameraByID(id);
  26383. if (camera) {
  26384. this.activeCamera = camera;
  26385. return camera;
  26386. }
  26387. return null;
  26388. };
  26389. /**
  26390. * sets the active camera of the scene using its name
  26391. * @param name defines the camera's name
  26392. * @returns the new active camera or null if none found.
  26393. */
  26394. Scene.prototype.setActiveCameraByName = function (name) {
  26395. var camera = this.getCameraByName(name);
  26396. if (camera) {
  26397. this.activeCamera = camera;
  26398. return camera;
  26399. }
  26400. return null;
  26401. };
  26402. /**
  26403. * get an animation group using its name
  26404. * @param name defines the material's name
  26405. * @return the animation group or null if none found.
  26406. */
  26407. Scene.prototype.getAnimationGroupByName = function (name) {
  26408. for (var index = 0; index < this.animationGroups.length; index++) {
  26409. if (this.animationGroups[index].name === name) {
  26410. return this.animationGroups[index];
  26411. }
  26412. }
  26413. return null;
  26414. };
  26415. /**
  26416. * get a material using its id
  26417. * @param id defines the material's ID
  26418. * @return the material or null if none found.
  26419. */
  26420. Scene.prototype.getMaterialByID = function (id) {
  26421. for (var index = 0; index < this.materials.length; index++) {
  26422. if (this.materials[index].id === id) {
  26423. return this.materials[index];
  26424. }
  26425. }
  26426. return null;
  26427. };
  26428. /**
  26429. * Gets a material using its name
  26430. * @param name defines the material's name
  26431. * @return the material or null if none found.
  26432. */
  26433. Scene.prototype.getMaterialByName = function (name) {
  26434. for (var index = 0; index < this.materials.length; index++) {
  26435. if (this.materials[index].name === name) {
  26436. return this.materials[index];
  26437. }
  26438. }
  26439. return null;
  26440. };
  26441. /**
  26442. * Gets a lens flare system using its name
  26443. * @param name defines the name to look for
  26444. * @returns the lens flare system or null if not found
  26445. */
  26446. Scene.prototype.getLensFlareSystemByName = function (name) {
  26447. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26448. if (this.lensFlareSystems[index].name === name) {
  26449. return this.lensFlareSystems[index];
  26450. }
  26451. }
  26452. return null;
  26453. };
  26454. /**
  26455. * Gets a lens flare system using its id
  26456. * @param id defines the id to look for
  26457. * @returns the lens flare system or null if not found
  26458. */
  26459. Scene.prototype.getLensFlareSystemByID = function (id) {
  26460. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26461. if (this.lensFlareSystems[index].id === id) {
  26462. return this.lensFlareSystems[index];
  26463. }
  26464. }
  26465. return null;
  26466. };
  26467. /**
  26468. * Gets a camera using its id
  26469. * @param id defines the id to look for
  26470. * @returns the camera or null if not found
  26471. */
  26472. Scene.prototype.getCameraByID = function (id) {
  26473. for (var index = 0; index < this.cameras.length; index++) {
  26474. if (this.cameras[index].id === id) {
  26475. return this.cameras[index];
  26476. }
  26477. }
  26478. return null;
  26479. };
  26480. /**
  26481. * Gets a camera using its unique id
  26482. * @param uniqueId defines the unique id to look for
  26483. * @returns the camera or null if not found
  26484. */
  26485. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26486. for (var index = 0; index < this.cameras.length; index++) {
  26487. if (this.cameras[index].uniqueId === uniqueId) {
  26488. return this.cameras[index];
  26489. }
  26490. }
  26491. return null;
  26492. };
  26493. /**
  26494. * Gets a camera using its name
  26495. * @param name defines the camera's name
  26496. * @return the camera or null if none found.
  26497. */
  26498. Scene.prototype.getCameraByName = function (name) {
  26499. for (var index = 0; index < this.cameras.length; index++) {
  26500. if (this.cameras[index].name === name) {
  26501. return this.cameras[index];
  26502. }
  26503. }
  26504. return null;
  26505. };
  26506. /**
  26507. * Gets a bone using its id
  26508. * @param id defines the bone's id
  26509. * @return the bone or null if not found
  26510. */
  26511. Scene.prototype.getBoneByID = function (id) {
  26512. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26513. var skeleton = this.skeletons[skeletonIndex];
  26514. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26515. if (skeleton.bones[boneIndex].id === id) {
  26516. return skeleton.bones[boneIndex];
  26517. }
  26518. }
  26519. }
  26520. return null;
  26521. };
  26522. /**
  26523. * Gets a bone using its id
  26524. * @param name defines the bone's name
  26525. * @return the bone or null if not found
  26526. */
  26527. Scene.prototype.getBoneByName = function (name) {
  26528. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26529. var skeleton = this.skeletons[skeletonIndex];
  26530. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26531. if (skeleton.bones[boneIndex].name === name) {
  26532. return skeleton.bones[boneIndex];
  26533. }
  26534. }
  26535. }
  26536. return null;
  26537. };
  26538. /**
  26539. * Gets a light node using its name
  26540. * @param name defines the the light's name
  26541. * @return the light or null if none found.
  26542. */
  26543. Scene.prototype.getLightByName = function (name) {
  26544. for (var index = 0; index < this.lights.length; index++) {
  26545. if (this.lights[index].name === name) {
  26546. return this.lights[index];
  26547. }
  26548. }
  26549. return null;
  26550. };
  26551. /**
  26552. * Gets a light node using its id
  26553. * @param id defines the light's id
  26554. * @return the light or null if none found.
  26555. */
  26556. Scene.prototype.getLightByID = function (id) {
  26557. for (var index = 0; index < this.lights.length; index++) {
  26558. if (this.lights[index].id === id) {
  26559. return this.lights[index];
  26560. }
  26561. }
  26562. return null;
  26563. };
  26564. /**
  26565. * Gets a light node using its scene-generated unique ID
  26566. * @param uniqueId defines the light's unique id
  26567. * @return the light or null if none found.
  26568. */
  26569. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26570. for (var index = 0; index < this.lights.length; index++) {
  26571. if (this.lights[index].uniqueId === uniqueId) {
  26572. return this.lights[index];
  26573. }
  26574. }
  26575. return null;
  26576. };
  26577. /**
  26578. * Gets a particle system by id
  26579. * @param id defines the particle system id
  26580. * @return the corresponding system or null if none found
  26581. */
  26582. Scene.prototype.getParticleSystemByID = function (id) {
  26583. for (var index = 0; index < this.particleSystems.length; index++) {
  26584. if (this.particleSystems[index].id === id) {
  26585. return this.particleSystems[index];
  26586. }
  26587. }
  26588. return null;
  26589. };
  26590. /**
  26591. * Gets a geometry using its ID
  26592. * @param id defines the geometry's id
  26593. * @return the geometry or null if none found.
  26594. */
  26595. Scene.prototype.getGeometryByID = function (id) {
  26596. for (var index = 0; index < this._geometries.length; index++) {
  26597. if (this._geometries[index].id === id) {
  26598. return this._geometries[index];
  26599. }
  26600. }
  26601. return null;
  26602. };
  26603. /**
  26604. * Add a new geometry to this scene
  26605. * @param geometry defines the geometry to be added to the scene.
  26606. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26607. * @return a boolean defining if the geometry was added or not
  26608. */
  26609. Scene.prototype.pushGeometry = function (geometry, force) {
  26610. if (!force && this.getGeometryByID(geometry.id)) {
  26611. return false;
  26612. }
  26613. this._geometries.push(geometry);
  26614. //notify the collision coordinator
  26615. if (this.collisionCoordinator) {
  26616. this.collisionCoordinator.onGeometryAdded(geometry);
  26617. }
  26618. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26619. return true;
  26620. };
  26621. /**
  26622. * Removes an existing geometry
  26623. * @param geometry defines the geometry to be removed from the scene
  26624. * @return a boolean defining if the geometry was removed or not
  26625. */
  26626. Scene.prototype.removeGeometry = function (geometry) {
  26627. var index = this._geometries.indexOf(geometry);
  26628. if (index > -1) {
  26629. this._geometries.splice(index, 1);
  26630. //notify the collision coordinator
  26631. if (this.collisionCoordinator) {
  26632. this.collisionCoordinator.onGeometryDeleted(geometry);
  26633. }
  26634. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26635. return true;
  26636. }
  26637. return false;
  26638. };
  26639. /**
  26640. * Gets the list of geometries attached to the scene
  26641. * @returns an array of Geometry
  26642. */
  26643. Scene.prototype.getGeometries = function () {
  26644. return this._geometries;
  26645. };
  26646. /**
  26647. * Gets the first added mesh found of a given ID
  26648. * @param id defines the id to search for
  26649. * @return the mesh found or null if not found at all
  26650. */
  26651. Scene.prototype.getMeshByID = function (id) {
  26652. for (var index = 0; index < this.meshes.length; index++) {
  26653. if (this.meshes[index].id === id) {
  26654. return this.meshes[index];
  26655. }
  26656. }
  26657. return null;
  26658. };
  26659. /**
  26660. * Gets a list of meshes using their id
  26661. * @param id defines the id to search for
  26662. * @returns a list of meshes
  26663. */
  26664. Scene.prototype.getMeshesByID = function (id) {
  26665. return this.meshes.filter(function (m) {
  26666. return m.id === id;
  26667. });
  26668. };
  26669. /**
  26670. * Gets the first added transform node found of a given ID
  26671. * @param id defines the id to search for
  26672. * @return the found transform node or null if not found at all.
  26673. */
  26674. Scene.prototype.getTransformNodeByID = function (id) {
  26675. for (var index = 0; index < this.transformNodes.length; index++) {
  26676. if (this.transformNodes[index].id === id) {
  26677. return this.transformNodes[index];
  26678. }
  26679. }
  26680. return null;
  26681. };
  26682. /**
  26683. * Gets a list of transform nodes using their id
  26684. * @param id defines the id to search for
  26685. * @returns a list of transform nodes
  26686. */
  26687. Scene.prototype.getTransformNodesByID = function (id) {
  26688. return this.transformNodes.filter(function (m) {
  26689. return m.id === id;
  26690. });
  26691. };
  26692. /**
  26693. * Gets a mesh with its auto-generated unique id
  26694. * @param uniqueId defines the unique id to search for
  26695. * @return the found mesh or null if not found at all.
  26696. */
  26697. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26698. for (var index = 0; index < this.meshes.length; index++) {
  26699. if (this.meshes[index].uniqueId === uniqueId) {
  26700. return this.meshes[index];
  26701. }
  26702. }
  26703. return null;
  26704. };
  26705. /**
  26706. * Gets a the last added mesh using a given id
  26707. * @param id defines the id to search for
  26708. * @return the found mesh or null if not found at all.
  26709. */
  26710. Scene.prototype.getLastMeshByID = function (id) {
  26711. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26712. if (this.meshes[index].id === id) {
  26713. return this.meshes[index];
  26714. }
  26715. }
  26716. return null;
  26717. };
  26718. /**
  26719. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26720. * @param id defines the id to search for
  26721. * @return the found node or null if not found at all
  26722. */
  26723. Scene.prototype.getLastEntryByID = function (id) {
  26724. var index;
  26725. for (index = this.meshes.length - 1; index >= 0; index--) {
  26726. if (this.meshes[index].id === id) {
  26727. return this.meshes[index];
  26728. }
  26729. }
  26730. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26731. if (this.transformNodes[index].id === id) {
  26732. return this.transformNodes[index];
  26733. }
  26734. }
  26735. for (index = this.cameras.length - 1; index >= 0; index--) {
  26736. if (this.cameras[index].id === id) {
  26737. return this.cameras[index];
  26738. }
  26739. }
  26740. for (index = this.lights.length - 1; index >= 0; index--) {
  26741. if (this.lights[index].id === id) {
  26742. return this.lights[index];
  26743. }
  26744. }
  26745. return null;
  26746. };
  26747. /**
  26748. * Gets a node (Mesh, Camera, Light) using a given id
  26749. * @param id defines the id to search for
  26750. * @return the found node or null if not found at all
  26751. */
  26752. Scene.prototype.getNodeByID = function (id) {
  26753. var mesh = this.getMeshByID(id);
  26754. if (mesh) {
  26755. return mesh;
  26756. }
  26757. var light = this.getLightByID(id);
  26758. if (light) {
  26759. return light;
  26760. }
  26761. var camera = this.getCameraByID(id);
  26762. if (camera) {
  26763. return camera;
  26764. }
  26765. var bone = this.getBoneByID(id);
  26766. return bone;
  26767. };
  26768. /**
  26769. * Gets a node (Mesh, Camera, Light) using a given name
  26770. * @param name defines the name to search for
  26771. * @return the found node or null if not found at all.
  26772. */
  26773. Scene.prototype.getNodeByName = function (name) {
  26774. var mesh = this.getMeshByName(name);
  26775. if (mesh) {
  26776. return mesh;
  26777. }
  26778. var light = this.getLightByName(name);
  26779. if (light) {
  26780. return light;
  26781. }
  26782. var camera = this.getCameraByName(name);
  26783. if (camera) {
  26784. return camera;
  26785. }
  26786. var bone = this.getBoneByName(name);
  26787. return bone;
  26788. };
  26789. /**
  26790. * Gets a mesh using a given name
  26791. * @param name defines the name to search for
  26792. * @return the found mesh or null if not found at all.
  26793. */
  26794. Scene.prototype.getMeshByName = function (name) {
  26795. for (var index = 0; index < this.meshes.length; index++) {
  26796. if (this.meshes[index].name === name) {
  26797. return this.meshes[index];
  26798. }
  26799. }
  26800. return null;
  26801. };
  26802. /**
  26803. * Gets a transform node using a given name
  26804. * @param name defines the name to search for
  26805. * @return the found transform node or null if not found at all.
  26806. */
  26807. Scene.prototype.getTransformNodeByName = function (name) {
  26808. for (var index = 0; index < this.transformNodes.length; index++) {
  26809. if (this.transformNodes[index].name === name) {
  26810. return this.transformNodes[index];
  26811. }
  26812. }
  26813. return null;
  26814. };
  26815. /**
  26816. * Gets a sound using a given name
  26817. * @param name defines the name to search for
  26818. * @return the found sound or null if not found at all.
  26819. */
  26820. Scene.prototype.getSoundByName = function (name) {
  26821. var index;
  26822. if (BABYLON.AudioEngine) {
  26823. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26824. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26825. return this.mainSoundTrack.soundCollection[index];
  26826. }
  26827. }
  26828. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26829. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26830. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26831. return this.soundTracks[sdIndex].soundCollection[index];
  26832. }
  26833. }
  26834. }
  26835. }
  26836. return null;
  26837. };
  26838. /**
  26839. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26840. * @param id defines the id to search for
  26841. * @return the found skeleton or null if not found at all.
  26842. */
  26843. Scene.prototype.getLastSkeletonByID = function (id) {
  26844. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26845. if (this.skeletons[index].id === id) {
  26846. return this.skeletons[index];
  26847. }
  26848. }
  26849. return null;
  26850. };
  26851. /**
  26852. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26853. * @param id defines the id to search for
  26854. * @return the found skeleton or null if not found at all.
  26855. */
  26856. Scene.prototype.getSkeletonById = function (id) {
  26857. for (var index = 0; index < this.skeletons.length; index++) {
  26858. if (this.skeletons[index].id === id) {
  26859. return this.skeletons[index];
  26860. }
  26861. }
  26862. return null;
  26863. };
  26864. /**
  26865. * Gets a skeleton using a given name
  26866. * @param name defines the name to search for
  26867. * @return the found skeleton or null if not found at all.
  26868. */
  26869. Scene.prototype.getSkeletonByName = function (name) {
  26870. for (var index = 0; index < this.skeletons.length; index++) {
  26871. if (this.skeletons[index].name === name) {
  26872. return this.skeletons[index];
  26873. }
  26874. }
  26875. return null;
  26876. };
  26877. /**
  26878. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26879. * @param id defines the id to search for
  26880. * @return the found morph target manager or null if not found at all.
  26881. */
  26882. Scene.prototype.getMorphTargetManagerById = function (id) {
  26883. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26884. if (this.morphTargetManagers[index].uniqueId === id) {
  26885. return this.morphTargetManagers[index];
  26886. }
  26887. }
  26888. return null;
  26889. };
  26890. /**
  26891. * Gets a boolean indicating if the given mesh is active
  26892. * @param mesh defines the mesh to look for
  26893. * @returns true if the mesh is in the active list
  26894. */
  26895. Scene.prototype.isActiveMesh = function (mesh) {
  26896. return (this._activeMeshes.indexOf(mesh) !== -1);
  26897. };
  26898. /**
  26899. * Return a the first highlight layer of the scene with a given name.
  26900. * @param name The name of the highlight layer to look for.
  26901. * @return The highlight layer if found otherwise null.
  26902. */
  26903. Scene.prototype.getHighlightLayerByName = function (name) {
  26904. for (var index = 0; index < this.effectLayers.length; index++) {
  26905. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26906. return this.effectLayers[index];
  26907. }
  26908. }
  26909. return null;
  26910. };
  26911. /**
  26912. * Return a the first highlight layer of the scene with a given name.
  26913. * @param name The name of the highlight layer to look for.
  26914. * @return The highlight layer if found otherwise null.
  26915. */
  26916. Scene.prototype.getGlowLayerByName = function (name) {
  26917. for (var index = 0; index < this.effectLayers.length; index++) {
  26918. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26919. return this.effectLayers[index];
  26920. }
  26921. }
  26922. return null;
  26923. };
  26924. Object.defineProperty(Scene.prototype, "uid", {
  26925. /**
  26926. * Return a unique id as a string which can serve as an identifier for the scene
  26927. */
  26928. get: function () {
  26929. if (!this._uid) {
  26930. this._uid = BABYLON.Tools.RandomId();
  26931. }
  26932. return this._uid;
  26933. },
  26934. enumerable: true,
  26935. configurable: true
  26936. });
  26937. /**
  26938. * Add an externaly attached data from its key.
  26939. * This method call will fail and return false, if such key already exists.
  26940. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26941. * @param key the unique key that identifies the data
  26942. * @param data the data object to associate to the key for this Engine instance
  26943. * @return true if no such key were already present and the data was added successfully, false otherwise
  26944. */
  26945. Scene.prototype.addExternalData = function (key, data) {
  26946. if (!this._externalData) {
  26947. this._externalData = new BABYLON.StringDictionary();
  26948. }
  26949. return this._externalData.add(key, data);
  26950. };
  26951. /**
  26952. * Get an externaly attached data from its key
  26953. * @param key the unique key that identifies the data
  26954. * @return the associated data, if present (can be null), or undefined if not present
  26955. */
  26956. Scene.prototype.getExternalData = function (key) {
  26957. if (!this._externalData) {
  26958. return null;
  26959. }
  26960. return this._externalData.get(key);
  26961. };
  26962. /**
  26963. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26964. * @param key the unique key that identifies the data
  26965. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26966. * @return the associated data, can be null if the factory returned null.
  26967. */
  26968. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26969. if (!this._externalData) {
  26970. this._externalData = new BABYLON.StringDictionary();
  26971. }
  26972. return this._externalData.getOrAddWithFactory(key, factory);
  26973. };
  26974. /**
  26975. * Remove an externaly attached data from the Engine instance
  26976. * @param key the unique key that identifies the data
  26977. * @return true if the data was successfully removed, false if it doesn't exist
  26978. */
  26979. Scene.prototype.removeExternalData = function (key) {
  26980. return this._externalData.remove(key);
  26981. };
  26982. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26983. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26984. if (mesh.showSubMeshesBoundingBox) {
  26985. var boundingInfo = subMesh.getBoundingInfo();
  26986. if (boundingInfo !== null && boundingInfo !== undefined) {
  26987. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26988. }
  26989. }
  26990. var material = subMesh.getMaterial();
  26991. if (material !== null && material !== undefined) {
  26992. // Render targets
  26993. if (material.getRenderTargetTextures !== undefined) {
  26994. if (this._processedMaterials.indexOf(material) === -1) {
  26995. this._processedMaterials.push(material);
  26996. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26997. }
  26998. }
  26999. // Dispatch
  27000. this._activeIndices.addCount(subMesh.indexCount, false);
  27001. this._renderingManager.dispatch(subMesh, mesh, material);
  27002. }
  27003. }
  27004. };
  27005. /**
  27006. * Clear the processed materials smart array preventing retention point in material dispose.
  27007. */
  27008. Scene.prototype.freeProcessedMaterials = function () {
  27009. this._processedMaterials.dispose();
  27010. };
  27011. /**
  27012. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27013. */
  27014. Scene.prototype.freeActiveMeshes = function () {
  27015. this._activeMeshes.dispose();
  27016. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27017. this.activeCamera._activeMeshes.dispose();
  27018. }
  27019. if (this.activeCameras) {
  27020. for (var i = 0; i < this.activeCameras.length; i++) {
  27021. var activeCamera = this.activeCameras[i];
  27022. if (activeCamera && activeCamera._activeMeshes) {
  27023. activeCamera._activeMeshes.dispose();
  27024. }
  27025. }
  27026. }
  27027. };
  27028. /**
  27029. * Clear the info related to rendering groups preventing retention points during dispose.
  27030. */
  27031. Scene.prototype.freeRenderingGroups = function () {
  27032. if (this._renderingManager) {
  27033. this._renderingManager.freeRenderingGroups();
  27034. }
  27035. if (this.textures) {
  27036. for (var i = 0; i < this.textures.length; i++) {
  27037. var texture = this.textures[i];
  27038. if (texture && texture.renderList) {
  27039. texture.freeRenderingGroups();
  27040. }
  27041. }
  27042. }
  27043. };
  27044. /** @hidden */
  27045. Scene.prototype._isInIntermediateRendering = function () {
  27046. return this._intermediateRendering;
  27047. };
  27048. /**
  27049. * Defines the current active mesh candidate provider
  27050. * @param provider defines the provider to use
  27051. */
  27052. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27053. this._activeMeshCandidateProvider = provider;
  27054. };
  27055. /**
  27056. * Gets the current active mesh candidate provider
  27057. * @returns the current active mesh candidate provider
  27058. */
  27059. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27060. return this._activeMeshCandidateProvider;
  27061. };
  27062. /**
  27063. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27064. * @returns the current scene
  27065. */
  27066. Scene.prototype.freezeActiveMeshes = function () {
  27067. if (!this.activeCamera) {
  27068. return this;
  27069. }
  27070. if (!this._frustumPlanes) {
  27071. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27072. }
  27073. this._evaluateActiveMeshes();
  27074. this._activeMeshesFrozen = true;
  27075. return this;
  27076. };
  27077. /**
  27078. * Use this function to restart evaluating active meshes on every frame
  27079. * @returns the current scene
  27080. */
  27081. Scene.prototype.unfreezeActiveMeshes = function () {
  27082. this._activeMeshesFrozen = false;
  27083. return this;
  27084. };
  27085. Scene.prototype._evaluateActiveMeshes = function () {
  27086. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27087. return;
  27088. }
  27089. if (!this.activeCamera) {
  27090. return;
  27091. }
  27092. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27093. this.activeCamera._activeMeshes.reset();
  27094. this._activeMeshes.reset();
  27095. this._renderingManager.reset();
  27096. this._processedMaterials.reset();
  27097. this._activeParticleSystems.reset();
  27098. this._activeSkeletons.reset();
  27099. this._softwareSkinnedMeshes.reset();
  27100. if (this._boundingBoxRenderer) {
  27101. this._boundingBoxRenderer.reset();
  27102. }
  27103. // Meshes
  27104. var meshes;
  27105. var len;
  27106. var checkIsEnabled = true;
  27107. // Determine mesh candidates
  27108. if (this._activeMeshCandidateProvider !== undefined) {
  27109. // Use _activeMeshCandidateProvider
  27110. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27111. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27112. if (meshes !== undefined) {
  27113. len = meshes.length;
  27114. }
  27115. else {
  27116. len = 0;
  27117. }
  27118. }
  27119. else if (this._selectionOctree !== undefined) {
  27120. // Octree
  27121. var selection = this._selectionOctree.select(this._frustumPlanes);
  27122. meshes = selection.data;
  27123. len = selection.length;
  27124. }
  27125. else {
  27126. // Full scene traversal
  27127. len = this.meshes.length;
  27128. meshes = this.meshes;
  27129. }
  27130. // Check each mesh
  27131. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27132. mesh = meshes[meshIndex];
  27133. if (mesh.isBlocked) {
  27134. continue;
  27135. }
  27136. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27137. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27138. continue;
  27139. }
  27140. mesh.computeWorldMatrix();
  27141. // Intersections
  27142. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27143. this._meshesForIntersections.pushNoDuplicate(mesh);
  27144. }
  27145. // Switch to current LOD
  27146. meshLOD = mesh.getLOD(this.activeCamera);
  27147. if (meshLOD === undefined || meshLOD === null) {
  27148. continue;
  27149. }
  27150. mesh._preActivate();
  27151. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27152. this._activeMeshes.push(mesh);
  27153. this.activeCamera._activeMeshes.push(mesh);
  27154. mesh._activate(this._renderId);
  27155. if (meshLOD !== mesh) {
  27156. meshLOD._activate(this._renderId);
  27157. }
  27158. this._activeMesh(mesh, meshLOD);
  27159. }
  27160. }
  27161. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27162. // Particle systems
  27163. if (this.particlesEnabled) {
  27164. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27165. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27166. var particleSystem = this.particleSystems[particleIndex];
  27167. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27168. continue;
  27169. }
  27170. var emitter = particleSystem.emitter;
  27171. if (!emitter.position || emitter.isEnabled()) {
  27172. this._activeParticleSystems.push(particleSystem);
  27173. particleSystem.animate();
  27174. this._renderingManager.dispatchParticles(particleSystem);
  27175. }
  27176. }
  27177. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27178. }
  27179. };
  27180. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27181. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27182. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27183. mesh.skeleton.prepare();
  27184. }
  27185. if (!mesh.computeBonesUsingShaders) {
  27186. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27187. }
  27188. }
  27189. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27190. var boundingInfo = sourceMesh.getBoundingInfo();
  27191. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27192. }
  27193. if (mesh !== undefined && mesh !== null
  27194. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27195. // Submeshes Octrees
  27196. var len;
  27197. var subMeshes;
  27198. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27199. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27200. len = intersections.length;
  27201. subMeshes = intersections.data;
  27202. }
  27203. else {
  27204. subMeshes = mesh.subMeshes;
  27205. len = subMeshes.length;
  27206. }
  27207. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27208. subMesh = subMeshes[subIndex];
  27209. this._evaluateSubMesh(subMesh, mesh);
  27210. }
  27211. }
  27212. };
  27213. /**
  27214. * Update the transform matrix to update from the current active camera
  27215. * @param force defines a boolean used to force the update even if cache is up to date
  27216. */
  27217. Scene.prototype.updateTransformMatrix = function (force) {
  27218. if (!this.activeCamera) {
  27219. return;
  27220. }
  27221. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27222. };
  27223. /**
  27224. * 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)
  27225. * @param alternateCamera defines the camera to use
  27226. */
  27227. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27228. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27229. };
  27230. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27231. if (camera && camera._skipRendering) {
  27232. return;
  27233. }
  27234. var engine = this._engine;
  27235. this.activeCamera = camera;
  27236. if (!this.activeCamera)
  27237. throw new Error("Active camera not set");
  27238. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27239. // Viewport
  27240. engine.setViewport(this.activeCamera.viewport);
  27241. // Camera
  27242. this.resetCachedMaterial();
  27243. this._renderId++;
  27244. this.updateTransformMatrix();
  27245. if (camera._alternateCamera) {
  27246. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27247. this._alternateRendering = true;
  27248. }
  27249. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27250. // Meshes
  27251. this._evaluateActiveMeshes();
  27252. // Software skinning
  27253. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27254. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27255. mesh.applySkeleton(mesh.skeleton);
  27256. }
  27257. // Render targets
  27258. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27259. var needsRestoreFrameBuffer = false;
  27260. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27261. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27262. }
  27263. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27264. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27265. }
  27266. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27267. this._intermediateRendering = true;
  27268. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27269. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27270. var renderTarget = this._renderTargets.data[renderIndex];
  27271. if (renderTarget._shouldRender()) {
  27272. this._renderId++;
  27273. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27274. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27275. }
  27276. }
  27277. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27278. this._intermediateRendering = false;
  27279. this._renderId++;
  27280. needsRestoreFrameBuffer = true; // Restore back buffer
  27281. }
  27282. // Render EffecttLayer Texture
  27283. var stencilState = this._engine.getStencilBuffer();
  27284. var renderEffects = false;
  27285. var needStencil = false;
  27286. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27287. this._intermediateRendering = true;
  27288. for (var i = 0; i < this.effectLayers.length; i++) {
  27289. var effectLayer = this.effectLayers[i];
  27290. if (effectLayer.shouldRender() &&
  27291. (!effectLayer.camera ||
  27292. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27293. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27294. renderEffects = true;
  27295. needStencil = needStencil || effectLayer.needStencil();
  27296. var renderTarget = effectLayer._mainTexture;
  27297. if (renderTarget._shouldRender()) {
  27298. this._renderId++;
  27299. renderTarget.render(false, false);
  27300. needsRestoreFrameBuffer = true;
  27301. }
  27302. }
  27303. }
  27304. this._intermediateRendering = false;
  27305. this._renderId++;
  27306. }
  27307. if (needsRestoreFrameBuffer) {
  27308. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27309. }
  27310. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27311. // Prepare Frame
  27312. this.postProcessManager._prepareFrame();
  27313. // Backgrounds
  27314. var layerIndex;
  27315. var layer;
  27316. if (this.layers.length) {
  27317. engine.setDepthBuffer(false);
  27318. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27319. layer = this.layers[layerIndex];
  27320. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27321. layer.render();
  27322. }
  27323. }
  27324. engine.setDepthBuffer(true);
  27325. }
  27326. // Activate effect Layer stencil
  27327. if (needStencil) {
  27328. this._engine.setStencilBuffer(true);
  27329. }
  27330. // Render
  27331. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27332. this._renderingManager.render(null, null, true, true);
  27333. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27334. // Restore effect Layer stencil
  27335. if (needStencil) {
  27336. this._engine.setStencilBuffer(stencilState);
  27337. }
  27338. // Bounding boxes
  27339. if (this._boundingBoxRenderer) {
  27340. this._boundingBoxRenderer.render();
  27341. }
  27342. // Lens flares
  27343. if (this.lensFlaresEnabled) {
  27344. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27345. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27346. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27347. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27348. lensFlareSystem.render();
  27349. }
  27350. }
  27351. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27352. }
  27353. // Effect Layer
  27354. if (renderEffects) {
  27355. engine.setDepthBuffer(false);
  27356. for (var i = 0; i < this.effectLayers.length; i++) {
  27357. if (this.effectLayers[i].shouldRender()) {
  27358. this.effectLayers[i].render();
  27359. }
  27360. }
  27361. engine.setDepthBuffer(true);
  27362. }
  27363. // Foregrounds
  27364. if (this.layers.length) {
  27365. engine.setDepthBuffer(false);
  27366. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27367. layer = this.layers[layerIndex];
  27368. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27369. layer.render();
  27370. }
  27371. }
  27372. engine.setDepthBuffer(true);
  27373. }
  27374. // Finalize frame
  27375. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27376. // Reset some special arrays
  27377. this._renderTargets.reset();
  27378. this._alternateRendering = false;
  27379. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27380. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27381. };
  27382. Scene.prototype._processSubCameras = function (camera) {
  27383. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27384. this._renderForCamera(camera);
  27385. return;
  27386. }
  27387. // rig cameras
  27388. for (var index = 0; index < camera._rigCameras.length; index++) {
  27389. this._renderForCamera(camera._rigCameras[index], camera);
  27390. }
  27391. this.activeCamera = camera;
  27392. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27393. };
  27394. Scene.prototype._checkIntersections = function () {
  27395. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27396. var sourceMesh = this._meshesForIntersections.data[index];
  27397. if (!sourceMesh.actionManager) {
  27398. continue;
  27399. }
  27400. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27401. var action = sourceMesh.actionManager.actions[actionIndex];
  27402. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27403. var parameters = action.getTriggerParameter();
  27404. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27405. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27406. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27407. if (areIntersecting && currentIntersectionInProgress === -1) {
  27408. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27409. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27410. sourceMesh._intersectionsInProgress.push(otherMesh);
  27411. }
  27412. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27413. sourceMesh._intersectionsInProgress.push(otherMesh);
  27414. }
  27415. }
  27416. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27417. //They intersected, and now they don't.
  27418. //is this trigger an exit trigger? execute an event.
  27419. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27420. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27421. }
  27422. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27423. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27424. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27425. return otherMesh === parameterMesh;
  27426. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27427. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27428. }
  27429. }
  27430. }
  27431. }
  27432. }
  27433. };
  27434. /**
  27435. * Render the scene
  27436. */
  27437. Scene.prototype.render = function () {
  27438. if (this.isDisposed) {
  27439. return;
  27440. }
  27441. this._activeParticles.fetchNewFrame();
  27442. this._totalVertices.fetchNewFrame();
  27443. this._activeIndices.fetchNewFrame();
  27444. this._activeBones.fetchNewFrame();
  27445. this._meshesForIntersections.reset();
  27446. this.resetCachedMaterial();
  27447. this.onBeforeAnimationsObservable.notifyObservers(this);
  27448. // Actions
  27449. if (this.actionManager) {
  27450. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27451. }
  27452. //Simplification Queue
  27453. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27454. this.simplificationQueue.executeNext();
  27455. }
  27456. if (this._engine.isDeterministicLockStep()) {
  27457. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27458. var defaultFPS = (60.0 / 1000.0);
  27459. var defaultFrameTime = 1000 / 60; // frame time in MS
  27460. if (this._physicsEngine) {
  27461. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27462. }
  27463. var stepsTaken = 0;
  27464. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27465. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27466. internalSteps = Math.min(internalSteps, maxSubSteps);
  27467. do {
  27468. this.onBeforeStepObservable.notifyObservers(this);
  27469. // Animations
  27470. this._animationRatio = defaultFrameTime * defaultFPS;
  27471. this._animate();
  27472. this.onAfterAnimationsObservable.notifyObservers(this);
  27473. // Physics
  27474. if (this._physicsEngine) {
  27475. this.onBeforePhysicsObservable.notifyObservers(this);
  27476. this._physicsEngine._step(defaultFrameTime / 1000);
  27477. this.onAfterPhysicsObservable.notifyObservers(this);
  27478. }
  27479. this.onAfterStepObservable.notifyObservers(this);
  27480. this._currentStepId++;
  27481. stepsTaken++;
  27482. deltaTime -= defaultFrameTime;
  27483. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27484. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27485. }
  27486. else {
  27487. // Animations
  27488. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27489. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27490. this._animate();
  27491. this.onAfterAnimationsObservable.notifyObservers(this);
  27492. // Physics
  27493. if (this._physicsEngine) {
  27494. this.onBeforePhysicsObservable.notifyObservers(this);
  27495. this._physicsEngine._step(deltaTime / 1000.0);
  27496. this.onAfterPhysicsObservable.notifyObservers(this);
  27497. }
  27498. }
  27499. // update gamepad manager
  27500. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27501. this._gamepadManager._checkGamepadsStatus();
  27502. }
  27503. // Update Cameras
  27504. if (this.activeCameras.length > 0) {
  27505. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27506. var camera = this.activeCameras[cameraIndex];
  27507. camera.update();
  27508. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27509. // rig cameras
  27510. for (var index = 0; index < camera._rigCameras.length; index++) {
  27511. camera._rigCameras[index].update();
  27512. }
  27513. }
  27514. }
  27515. }
  27516. else if (this.activeCamera) {
  27517. this.activeCamera.update();
  27518. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27519. // rig cameras
  27520. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27521. this.activeCamera._rigCameras[index].update();
  27522. }
  27523. }
  27524. }
  27525. // Before render
  27526. this.onBeforeRenderObservable.notifyObservers(this);
  27527. // Customs render targets
  27528. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27529. var engine = this.getEngine();
  27530. var currentActiveCamera = this.activeCamera;
  27531. if (this.renderTargetsEnabled) {
  27532. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27533. this._intermediateRendering = true;
  27534. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27535. var renderTarget = this.customRenderTargets[customIndex];
  27536. if (renderTarget._shouldRender()) {
  27537. this._renderId++;
  27538. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27539. if (!this.activeCamera)
  27540. throw new Error("Active camera not set");
  27541. // Viewport
  27542. engine.setViewport(this.activeCamera.viewport);
  27543. // Camera
  27544. this.updateTransformMatrix();
  27545. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27546. }
  27547. }
  27548. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27549. this._intermediateRendering = false;
  27550. this._renderId++;
  27551. }
  27552. // Restore back buffer
  27553. if (this.customRenderTargets.length > 0) {
  27554. engine.restoreDefaultFramebuffer();
  27555. }
  27556. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27557. this.activeCamera = currentActiveCamera;
  27558. // Procedural textures
  27559. if (this.proceduralTexturesEnabled) {
  27560. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27561. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27562. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27563. if (proceduralTexture._shouldRender()) {
  27564. proceduralTexture.render();
  27565. }
  27566. }
  27567. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27568. }
  27569. // Clear
  27570. if (this.autoClearDepthAndStencil || this.autoClear) {
  27571. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27572. }
  27573. // Shadows
  27574. if (this.shadowsEnabled) {
  27575. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27576. var light = this.lights[lightIndex];
  27577. var shadowGenerator = light.getShadowGenerator();
  27578. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27579. var shadowMap = (shadowGenerator.getShadowMap());
  27580. if (this.textures.indexOf(shadowMap) !== -1) {
  27581. this._renderTargets.push(shadowMap);
  27582. }
  27583. }
  27584. }
  27585. }
  27586. // Depth renderer
  27587. for (var key in this._depthRenderer) {
  27588. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27589. }
  27590. // Geometry renderer
  27591. if (this._geometryBufferRenderer) {
  27592. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27593. }
  27594. // RenderPipeline
  27595. if (this._postProcessRenderPipelineManager) {
  27596. this._postProcessRenderPipelineManager.update();
  27597. }
  27598. // Multi-cameras?
  27599. if (this.activeCameras.length > 0) {
  27600. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27601. if (cameraIndex > 0) {
  27602. this._engine.clear(null, false, true, true);
  27603. }
  27604. this._processSubCameras(this.activeCameras[cameraIndex]);
  27605. }
  27606. }
  27607. else {
  27608. if (!this.activeCamera) {
  27609. throw new Error("No camera defined");
  27610. }
  27611. this._processSubCameras(this.activeCamera);
  27612. }
  27613. // Intersection checks
  27614. this._checkIntersections();
  27615. // Update the audio listener attached to the camera
  27616. if (BABYLON.AudioEngine) {
  27617. this._updateAudioParameters();
  27618. }
  27619. // After render
  27620. if (this.afterRender) {
  27621. this.afterRender();
  27622. }
  27623. this.onAfterRenderObservable.notifyObservers(this);
  27624. // Cleaning
  27625. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27626. var data = this._toBeDisposed.data[index];
  27627. if (data) {
  27628. data.dispose();
  27629. }
  27630. this._toBeDisposed[index] = null;
  27631. }
  27632. this._toBeDisposed.reset();
  27633. if (this.dumpNextRenderTargets) {
  27634. this.dumpNextRenderTargets = false;
  27635. }
  27636. this._activeBones.addCount(0, true);
  27637. this._activeIndices.addCount(0, true);
  27638. this._activeParticles.addCount(0, true);
  27639. };
  27640. Scene.prototype._updateAudioParameters = function () {
  27641. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27642. return;
  27643. }
  27644. var listeningCamera;
  27645. var audioEngine = BABYLON.Engine.audioEngine;
  27646. if (this.activeCameras.length > 0) {
  27647. listeningCamera = this.activeCameras[0];
  27648. }
  27649. else {
  27650. listeningCamera = this.activeCamera;
  27651. }
  27652. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27653. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27654. // for VR cameras
  27655. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27656. listeningCamera = listeningCamera.rigCameras[0];
  27657. }
  27658. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27659. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27660. cameraDirection.normalize();
  27661. // To avoid some errors on GearVR
  27662. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27663. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27664. }
  27665. var i;
  27666. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27667. var sound = this.mainSoundTrack.soundCollection[i];
  27668. if (sound.useCustomAttenuation) {
  27669. sound.updateDistanceFromListener();
  27670. }
  27671. }
  27672. for (i = 0; i < this.soundTracks.length; i++) {
  27673. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27674. sound = this.soundTracks[i].soundCollection[j];
  27675. if (sound.useCustomAttenuation) {
  27676. sound.updateDistanceFromListener();
  27677. }
  27678. }
  27679. }
  27680. }
  27681. };
  27682. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27683. // Audio
  27684. /**
  27685. * Gets or sets if audio support is enabled
  27686. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27687. */
  27688. get: function () {
  27689. return this._audioEnabled;
  27690. },
  27691. set: function (value) {
  27692. this._audioEnabled = value;
  27693. if (BABYLON.AudioEngine) {
  27694. if (this._audioEnabled) {
  27695. this._enableAudio();
  27696. }
  27697. else {
  27698. this._disableAudio();
  27699. }
  27700. }
  27701. },
  27702. enumerable: true,
  27703. configurable: true
  27704. });
  27705. Scene.prototype._disableAudio = function () {
  27706. var i;
  27707. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27708. this.mainSoundTrack.soundCollection[i].pause();
  27709. }
  27710. for (i = 0; i < this.soundTracks.length; i++) {
  27711. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27712. this.soundTracks[i].soundCollection[j].pause();
  27713. }
  27714. }
  27715. };
  27716. Scene.prototype._enableAudio = function () {
  27717. var i;
  27718. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27719. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27720. this.mainSoundTrack.soundCollection[i].play();
  27721. }
  27722. }
  27723. for (i = 0; i < this.soundTracks.length; i++) {
  27724. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27725. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27726. this.soundTracks[i].soundCollection[j].play();
  27727. }
  27728. }
  27729. }
  27730. };
  27731. Object.defineProperty(Scene.prototype, "headphone", {
  27732. /**
  27733. * Gets or sets if audio will be output to headphones
  27734. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27735. */
  27736. get: function () {
  27737. return this._headphone;
  27738. },
  27739. set: function (value) {
  27740. this._headphone = value;
  27741. if (BABYLON.AudioEngine) {
  27742. if (this._headphone) {
  27743. this._switchAudioModeForHeadphones();
  27744. }
  27745. else {
  27746. this._switchAudioModeForNormalSpeakers();
  27747. }
  27748. }
  27749. },
  27750. enumerable: true,
  27751. configurable: true
  27752. });
  27753. Scene.prototype._switchAudioModeForHeadphones = function () {
  27754. this.mainSoundTrack.switchPanningModelToHRTF();
  27755. for (var i = 0; i < this.soundTracks.length; i++) {
  27756. this.soundTracks[i].switchPanningModelToHRTF();
  27757. }
  27758. };
  27759. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27760. this.mainSoundTrack.switchPanningModelToEqualPower();
  27761. for (var i = 0; i < this.soundTracks.length; i++) {
  27762. this.soundTracks[i].switchPanningModelToEqualPower();
  27763. }
  27764. };
  27765. /**
  27766. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27767. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27768. * @returns the created depth renderer
  27769. */
  27770. Scene.prototype.enableDepthRenderer = function (camera) {
  27771. camera = camera || this.activeCamera;
  27772. if (!camera) {
  27773. throw "No camera available to enable depth renderer";
  27774. }
  27775. if (!this._depthRenderer[camera.id]) {
  27776. var textureType = 0;
  27777. if (this._engine.getCaps().textureHalfFloatRender) {
  27778. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27779. }
  27780. else if (this._engine.getCaps().textureFloatRender) {
  27781. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27782. }
  27783. else {
  27784. throw "Depth renderer does not support int texture type";
  27785. }
  27786. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27787. }
  27788. return this._depthRenderer[camera.id];
  27789. };
  27790. /**
  27791. * Disables a depth renderer for a given camera
  27792. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27793. */
  27794. Scene.prototype.disableDepthRenderer = function (camera) {
  27795. camera = camera || this.activeCamera;
  27796. if (!camera || !this._depthRenderer[camera.id]) {
  27797. return;
  27798. }
  27799. this._depthRenderer[camera.id].dispose();
  27800. delete this._depthRenderer[camera.id];
  27801. };
  27802. /**
  27803. * Enables a GeometryBufferRender and associates it with the scene
  27804. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27805. * @returns the GeometryBufferRenderer
  27806. */
  27807. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27808. if (ratio === void 0) { ratio = 1; }
  27809. if (this._geometryBufferRenderer) {
  27810. return this._geometryBufferRenderer;
  27811. }
  27812. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27813. if (!this._geometryBufferRenderer.isSupported) {
  27814. this._geometryBufferRenderer = null;
  27815. }
  27816. return this._geometryBufferRenderer;
  27817. };
  27818. /**
  27819. * Disables the GeometryBufferRender associated with the scene
  27820. */
  27821. Scene.prototype.disableGeometryBufferRenderer = function () {
  27822. if (!this._geometryBufferRenderer) {
  27823. return;
  27824. }
  27825. this._geometryBufferRenderer.dispose();
  27826. this._geometryBufferRenderer = null;
  27827. };
  27828. /**
  27829. * Freeze all materials
  27830. * A frozen material will not be updatable but should be faster to render
  27831. */
  27832. Scene.prototype.freezeMaterials = function () {
  27833. for (var i = 0; i < this.materials.length; i++) {
  27834. this.materials[i].freeze();
  27835. }
  27836. };
  27837. /**
  27838. * Unfreeze all materials
  27839. * A frozen material will not be updatable but should be faster to render
  27840. */
  27841. Scene.prototype.unfreezeMaterials = function () {
  27842. for (var i = 0; i < this.materials.length; i++) {
  27843. this.materials[i].unfreeze();
  27844. }
  27845. };
  27846. /**
  27847. * Releases all held ressources
  27848. */
  27849. Scene.prototype.dispose = function () {
  27850. this.beforeRender = null;
  27851. this.afterRender = null;
  27852. this.skeletons = [];
  27853. this.morphTargetManagers = [];
  27854. this.importedMeshesFiles = new Array();
  27855. this.stopAllAnimations();
  27856. this.resetCachedMaterial();
  27857. for (var key in this._depthRenderer) {
  27858. this._depthRenderer[key].dispose();
  27859. }
  27860. if (this._gamepadManager) {
  27861. this._gamepadManager.dispose();
  27862. this._gamepadManager = null;
  27863. }
  27864. // Smart arrays
  27865. if (this.activeCamera) {
  27866. this.activeCamera._activeMeshes.dispose();
  27867. this.activeCamera = null;
  27868. }
  27869. this._activeMeshes.dispose();
  27870. this._renderingManager.dispose();
  27871. this._processedMaterials.dispose();
  27872. this._activeParticleSystems.dispose();
  27873. this._activeSkeletons.dispose();
  27874. this._softwareSkinnedMeshes.dispose();
  27875. this._renderTargets.dispose();
  27876. this._registeredForLateAnimationBindings.dispose();
  27877. if (this._boundingBoxRenderer) {
  27878. this._boundingBoxRenderer.dispose();
  27879. }
  27880. this._meshesForIntersections.dispose();
  27881. this._toBeDisposed.dispose();
  27882. // Abort active requests
  27883. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27884. var request = _a[_i];
  27885. request.abort();
  27886. }
  27887. // Debug layer
  27888. if (this._debugLayer) {
  27889. this._debugLayer.hide();
  27890. }
  27891. // Events
  27892. this.onDisposeObservable.notifyObservers(this);
  27893. this.onDisposeObservable.clear();
  27894. this.onBeforeRenderObservable.clear();
  27895. this.onAfterRenderObservable.clear();
  27896. this.onBeforeRenderTargetsRenderObservable.clear();
  27897. this.onAfterRenderTargetsRenderObservable.clear();
  27898. this.onAfterStepObservable.clear();
  27899. this.onBeforeStepObservable.clear();
  27900. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27901. this.onAfterActiveMeshesEvaluationObservable.clear();
  27902. this.onBeforeParticlesRenderingObservable.clear();
  27903. this.onAfterParticlesRenderingObservable.clear();
  27904. this.onBeforeSpritesRenderingObservable.clear();
  27905. this.onAfterSpritesRenderingObservable.clear();
  27906. this.onBeforeDrawPhaseObservable.clear();
  27907. this.onAfterDrawPhaseObservable.clear();
  27908. this.onBeforePhysicsObservable.clear();
  27909. this.onAfterPhysicsObservable.clear();
  27910. this.onBeforeAnimationsObservable.clear();
  27911. this.onAfterAnimationsObservable.clear();
  27912. this.onDataLoadedObservable.clear();
  27913. this.detachControl();
  27914. // Release sounds & sounds tracks
  27915. if (BABYLON.AudioEngine) {
  27916. this.disposeSounds();
  27917. }
  27918. // VR Helper
  27919. if (this.VRHelper) {
  27920. this.VRHelper.dispose();
  27921. }
  27922. // Detach cameras
  27923. var canvas = this._engine.getRenderingCanvas();
  27924. if (canvas) {
  27925. var index;
  27926. for (index = 0; index < this.cameras.length; index++) {
  27927. this.cameras[index].detachControl(canvas);
  27928. }
  27929. }
  27930. // Release animation groups
  27931. while (this.animationGroups.length) {
  27932. this.animationGroups[0].dispose();
  27933. }
  27934. // Release lights
  27935. while (this.lights.length) {
  27936. this.lights[0].dispose();
  27937. }
  27938. // Release meshes
  27939. while (this.meshes.length) {
  27940. this.meshes[0].dispose(true);
  27941. }
  27942. while (this.transformNodes.length) {
  27943. this.removeTransformNode(this.transformNodes[0]);
  27944. }
  27945. // Release cameras
  27946. while (this.cameras.length) {
  27947. this.cameras[0].dispose();
  27948. }
  27949. // Release materials
  27950. if (this.defaultMaterial) {
  27951. this.defaultMaterial.dispose();
  27952. }
  27953. while (this.multiMaterials.length) {
  27954. this.multiMaterials[0].dispose();
  27955. }
  27956. while (this.materials.length) {
  27957. this.materials[0].dispose();
  27958. }
  27959. // Release particles
  27960. while (this.particleSystems.length) {
  27961. this.particleSystems[0].dispose();
  27962. }
  27963. // Release sprites
  27964. while (this.spriteManagers.length) {
  27965. this.spriteManagers[0].dispose();
  27966. }
  27967. // Release postProcesses
  27968. while (this.postProcesses.length) {
  27969. this.postProcesses[0].dispose();
  27970. }
  27971. // Release layers
  27972. while (this.layers.length) {
  27973. this.layers[0].dispose();
  27974. }
  27975. while (this.effectLayers.length) {
  27976. this.effectLayers[0].dispose();
  27977. }
  27978. // Release textures
  27979. while (this.textures.length) {
  27980. this.textures[0].dispose();
  27981. }
  27982. // Release UBO
  27983. this._sceneUbo.dispose();
  27984. if (this._alternateSceneUbo) {
  27985. this._alternateSceneUbo.dispose();
  27986. }
  27987. // Post-processes
  27988. this.postProcessManager.dispose();
  27989. if (this._postProcessRenderPipelineManager) {
  27990. this._postProcessRenderPipelineManager.dispose();
  27991. }
  27992. // Physics
  27993. if (this._physicsEngine) {
  27994. this.disablePhysicsEngine();
  27995. }
  27996. // Remove from engine
  27997. index = this._engine.scenes.indexOf(this);
  27998. if (index > -1) {
  27999. this._engine.scenes.splice(index, 1);
  28000. }
  28001. this._engine.wipeCaches(true);
  28002. this._isDisposed = true;
  28003. };
  28004. Object.defineProperty(Scene.prototype, "isDisposed", {
  28005. /**
  28006. * Gets if the scene is already disposed
  28007. */
  28008. get: function () {
  28009. return this._isDisposed;
  28010. },
  28011. enumerable: true,
  28012. configurable: true
  28013. });
  28014. /**
  28015. * Releases sounds & soundtracks
  28016. */
  28017. Scene.prototype.disposeSounds = function () {
  28018. if (!this._mainSoundTrack) {
  28019. return;
  28020. }
  28021. this.mainSoundTrack.dispose();
  28022. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28023. this.soundTracks[scIndex].dispose();
  28024. }
  28025. };
  28026. // Octrees
  28027. /**
  28028. * Get the world extend vectors with an optional filter
  28029. *
  28030. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28031. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28032. */
  28033. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28034. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28035. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28036. filterPredicate = filterPredicate || (function () { return true; });
  28037. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28038. mesh.computeWorldMatrix(true);
  28039. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28040. return;
  28041. }
  28042. var boundingInfo = mesh.getBoundingInfo();
  28043. var minBox = boundingInfo.boundingBox.minimumWorld;
  28044. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28045. BABYLON.Tools.CheckExtends(minBox, min, max);
  28046. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28047. });
  28048. return {
  28049. min: min,
  28050. max: max
  28051. };
  28052. };
  28053. /**
  28054. * Creates or updates the octree used to boost selection (picking)
  28055. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28056. * @param maxCapacity defines the maximum capacity per leaf
  28057. * @param maxDepth defines the maximum depth of the octree
  28058. * @returns an octree of AbstractMesh
  28059. */
  28060. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28061. if (maxCapacity === void 0) { maxCapacity = 64; }
  28062. if (maxDepth === void 0) { maxDepth = 2; }
  28063. if (!this._selectionOctree) {
  28064. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28065. }
  28066. var worldExtends = this.getWorldExtends();
  28067. // Update octree
  28068. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28069. return this._selectionOctree;
  28070. };
  28071. // Picking
  28072. /**
  28073. * Creates a ray that can be used to pick in the scene
  28074. * @param x defines the x coordinate of the origin (on-screen)
  28075. * @param y defines the y coordinate of the origin (on-screen)
  28076. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28077. * @param camera defines the camera to use for the picking
  28078. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28079. * @returns a Ray
  28080. */
  28081. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28082. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28083. var result = BABYLON.Ray.Zero();
  28084. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28085. return result;
  28086. };
  28087. /**
  28088. * Creates a ray that can be used to pick in the scene
  28089. * @param x defines the x coordinate of the origin (on-screen)
  28090. * @param y defines the y coordinate of the origin (on-screen)
  28091. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28092. * @param result defines the ray where to store the picking ray
  28093. * @param camera defines the camera to use for the picking
  28094. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28095. * @returns the current scene
  28096. */
  28097. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28098. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28099. var engine = this._engine;
  28100. if (!camera) {
  28101. if (!this.activeCamera)
  28102. throw new Error("Active camera not set");
  28103. camera = this.activeCamera;
  28104. }
  28105. var cameraViewport = camera.viewport;
  28106. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28107. // Moving coordinates to local viewport world
  28108. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28109. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28110. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28111. return this;
  28112. };
  28113. /**
  28114. * Creates a ray that can be used to pick in the scene
  28115. * @param x defines the x coordinate of the origin (on-screen)
  28116. * @param y defines the y coordinate of the origin (on-screen)
  28117. * @param camera defines the camera to use for the picking
  28118. * @returns a Ray
  28119. */
  28120. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28121. var result = BABYLON.Ray.Zero();
  28122. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28123. return result;
  28124. };
  28125. /**
  28126. * Creates a ray that can be used to pick in the scene
  28127. * @param x defines the x coordinate of the origin (on-screen)
  28128. * @param y defines the y coordinate of the origin (on-screen)
  28129. * @param result defines the ray where to store the picking ray
  28130. * @param camera defines the camera to use for the picking
  28131. * @returns the current scene
  28132. */
  28133. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28134. if (!BABYLON.PickingInfo) {
  28135. return this;
  28136. }
  28137. var engine = this._engine;
  28138. if (!camera) {
  28139. if (!this.activeCamera)
  28140. throw new Error("Active camera not set");
  28141. camera = this.activeCamera;
  28142. }
  28143. var cameraViewport = camera.viewport;
  28144. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28145. var identity = BABYLON.Matrix.Identity();
  28146. // Moving coordinates to local viewport world
  28147. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28148. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28149. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28150. return this;
  28151. };
  28152. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28153. if (!BABYLON.PickingInfo) {
  28154. return null;
  28155. }
  28156. var pickingInfo = null;
  28157. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28158. var mesh = this.meshes[meshIndex];
  28159. if (predicate) {
  28160. if (!predicate(mesh)) {
  28161. continue;
  28162. }
  28163. }
  28164. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28165. continue;
  28166. }
  28167. var world = mesh.getWorldMatrix();
  28168. var ray = rayFunction(world);
  28169. var result = mesh.intersects(ray, fastCheck);
  28170. if (!result || !result.hit)
  28171. continue;
  28172. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28173. continue;
  28174. pickingInfo = result;
  28175. if (fastCheck) {
  28176. break;
  28177. }
  28178. }
  28179. return pickingInfo || new BABYLON.PickingInfo();
  28180. };
  28181. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28182. if (!BABYLON.PickingInfo) {
  28183. return null;
  28184. }
  28185. var pickingInfos = new Array();
  28186. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28187. var mesh = this.meshes[meshIndex];
  28188. if (predicate) {
  28189. if (!predicate(mesh)) {
  28190. continue;
  28191. }
  28192. }
  28193. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28194. continue;
  28195. }
  28196. var world = mesh.getWorldMatrix();
  28197. var ray = rayFunction(world);
  28198. var result = mesh.intersects(ray, false);
  28199. if (!result || !result.hit)
  28200. continue;
  28201. pickingInfos.push(result);
  28202. }
  28203. return pickingInfos;
  28204. };
  28205. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28206. if (!BABYLON.PickingInfo) {
  28207. return null;
  28208. }
  28209. var pickingInfo = null;
  28210. if (!camera) {
  28211. if (!this.activeCamera) {
  28212. return null;
  28213. }
  28214. camera = this.activeCamera;
  28215. }
  28216. if (this.spriteManagers.length > 0) {
  28217. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28218. var spriteManager = this.spriteManagers[spriteIndex];
  28219. if (!spriteManager.isPickable) {
  28220. continue;
  28221. }
  28222. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28223. if (!result || !result.hit)
  28224. continue;
  28225. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28226. continue;
  28227. pickingInfo = result;
  28228. if (fastCheck) {
  28229. break;
  28230. }
  28231. }
  28232. }
  28233. return pickingInfo || new BABYLON.PickingInfo();
  28234. };
  28235. /** Launch a ray to try to pick a mesh in the scene
  28236. * @param x position on screen
  28237. * @param y position on screen
  28238. * @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
  28239. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28240. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28241. * @returns a PickingInfo
  28242. */
  28243. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28244. var _this = this;
  28245. if (!BABYLON.PickingInfo) {
  28246. return null;
  28247. }
  28248. return this._internalPick(function (world) {
  28249. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28250. return _this._tempPickingRay;
  28251. }, predicate, fastCheck);
  28252. };
  28253. /** Launch a ray to try to pick a sprite in the scene
  28254. * @param x position on screen
  28255. * @param y position on screen
  28256. * @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
  28257. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28258. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28259. * @returns a PickingInfo
  28260. */
  28261. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28262. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28263. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28264. };
  28265. /** Use the given ray to pick a mesh in the scene
  28266. * @param ray The ray to use to pick meshes
  28267. * @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
  28268. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28269. * @returns a PickingInfo
  28270. */
  28271. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28272. var _this = this;
  28273. return this._internalPick(function (world) {
  28274. if (!_this._pickWithRayInverseMatrix) {
  28275. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28276. }
  28277. world.invertToRef(_this._pickWithRayInverseMatrix);
  28278. if (!_this._cachedRayForTransform) {
  28279. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28280. }
  28281. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28282. return _this._cachedRayForTransform;
  28283. }, predicate, fastCheck);
  28284. };
  28285. /**
  28286. * Launch a ray to try to pick a mesh in the scene
  28287. * @param x X position on screen
  28288. * @param y Y position on screen
  28289. * @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
  28290. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28291. * @returns an array of PickingInfo
  28292. */
  28293. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28294. var _this = this;
  28295. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28296. };
  28297. /**
  28298. * Launch a ray to try to pick a mesh in the scene
  28299. * @param ray Ray to use
  28300. * @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
  28301. * @returns an array of PickingInfo
  28302. */
  28303. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28304. var _this = this;
  28305. return this._internalMultiPick(function (world) {
  28306. if (!_this._pickWithRayInverseMatrix) {
  28307. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28308. }
  28309. world.invertToRef(_this._pickWithRayInverseMatrix);
  28310. if (!_this._cachedRayForTransform) {
  28311. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28312. }
  28313. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28314. return _this._cachedRayForTransform;
  28315. }, predicate);
  28316. };
  28317. /**
  28318. * Force the value of meshUnderPointer
  28319. * @param mesh defines the mesh to use
  28320. */
  28321. Scene.prototype.setPointerOverMesh = function (mesh) {
  28322. if (this._pointerOverMesh === mesh) {
  28323. return;
  28324. }
  28325. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28326. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28327. }
  28328. this._pointerOverMesh = mesh;
  28329. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28330. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28331. }
  28332. };
  28333. /**
  28334. * Gets the mesh under the pointer
  28335. * @returns a Mesh or null if no mesh is under the pointer
  28336. */
  28337. Scene.prototype.getPointerOverMesh = function () {
  28338. return this._pointerOverMesh;
  28339. };
  28340. /**
  28341. * Force the sprite under the pointer
  28342. * @param sprite defines the sprite to use
  28343. */
  28344. Scene.prototype.setPointerOverSprite = function (sprite) {
  28345. if (this._pointerOverSprite === sprite) {
  28346. return;
  28347. }
  28348. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28349. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28350. }
  28351. this._pointerOverSprite = sprite;
  28352. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28353. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28354. }
  28355. };
  28356. /**
  28357. * Gets the sprite under the pointer
  28358. * @returns a Sprite or null if no sprite is under the pointer
  28359. */
  28360. Scene.prototype.getPointerOverSprite = function () {
  28361. return this._pointerOverSprite;
  28362. };
  28363. // Physics
  28364. /**
  28365. * Gets the current physics engine
  28366. * @returns a PhysicsEngine or null if none attached
  28367. */
  28368. Scene.prototype.getPhysicsEngine = function () {
  28369. return this._physicsEngine;
  28370. };
  28371. /**
  28372. * Enables physics to the current scene
  28373. * @param gravity defines the scene's gravity for the physics engine
  28374. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28375. * @return a boolean indicating if the physics engine was initialized
  28376. */
  28377. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28378. if (gravity === void 0) { gravity = null; }
  28379. if (this._physicsEngine) {
  28380. return true;
  28381. }
  28382. try {
  28383. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28384. return true;
  28385. }
  28386. catch (e) {
  28387. BABYLON.Tools.Error(e.message);
  28388. return false;
  28389. }
  28390. };
  28391. /**
  28392. * Disables and disposes the physics engine associated with the scene
  28393. */
  28394. Scene.prototype.disablePhysicsEngine = function () {
  28395. if (!this._physicsEngine) {
  28396. return;
  28397. }
  28398. this._physicsEngine.dispose();
  28399. this._physicsEngine = null;
  28400. };
  28401. /**
  28402. * Gets a boolean indicating if there is an active physics engine
  28403. * @returns a boolean indicating if there is an active physics engine
  28404. */
  28405. Scene.prototype.isPhysicsEnabled = function () {
  28406. return this._physicsEngine !== undefined;
  28407. };
  28408. /**
  28409. * Deletes a physics compound impostor
  28410. * @param compound defines the compound to delete
  28411. */
  28412. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28413. var mesh = compound.parts[0].mesh;
  28414. if (mesh.physicsImpostor) {
  28415. mesh.physicsImpostor.dispose( /*true*/);
  28416. mesh.physicsImpostor = null;
  28417. }
  28418. };
  28419. // Misc.
  28420. /** @hidden */
  28421. Scene.prototype._rebuildGeometries = function () {
  28422. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28423. var geometry = _a[_i];
  28424. geometry._rebuild();
  28425. }
  28426. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28427. var mesh = _c[_b];
  28428. mesh._rebuild();
  28429. }
  28430. if (this.postProcessManager) {
  28431. this.postProcessManager._rebuild();
  28432. }
  28433. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28434. var layer = _e[_d];
  28435. layer._rebuild();
  28436. }
  28437. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28438. var effectLayer = _g[_f];
  28439. effectLayer._rebuild();
  28440. }
  28441. if (this._boundingBoxRenderer) {
  28442. this._boundingBoxRenderer._rebuild();
  28443. }
  28444. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28445. var system = _j[_h];
  28446. system.rebuild();
  28447. }
  28448. if (this._postProcessRenderPipelineManager) {
  28449. this._postProcessRenderPipelineManager._rebuild();
  28450. }
  28451. };
  28452. /** @hidden */
  28453. Scene.prototype._rebuildTextures = function () {
  28454. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28455. var texture = _a[_i];
  28456. texture._rebuild();
  28457. }
  28458. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28459. };
  28460. /**
  28461. * Creates a default light for the scene.
  28462. * @param replace Whether to replace the existing lights in the scene.
  28463. */
  28464. Scene.prototype.createDefaultLight = function (replace) {
  28465. if (replace === void 0) { replace = false; }
  28466. // Dispose existing light in replace mode.
  28467. if (replace) {
  28468. if (this.lights) {
  28469. for (var i = 0; i < this.lights.length; i++) {
  28470. this.lights[i].dispose();
  28471. }
  28472. }
  28473. }
  28474. // Light
  28475. if (this.lights.length === 0) {
  28476. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28477. }
  28478. };
  28479. /**
  28480. * Creates a default camera for the scene.
  28481. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28482. * @param replace Whether to replace the existing active camera in the scene.
  28483. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28484. */
  28485. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28486. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28487. if (replace === void 0) { replace = false; }
  28488. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28489. // Dispose existing camera in replace mode.
  28490. if (replace) {
  28491. if (this.activeCamera) {
  28492. this.activeCamera.dispose();
  28493. this.activeCamera = null;
  28494. }
  28495. }
  28496. // Camera
  28497. if (!this.activeCamera) {
  28498. var worldExtends = this.getWorldExtends();
  28499. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28500. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28501. var camera;
  28502. var radius = worldSize.length() * 1.5;
  28503. // empty scene scenario!
  28504. if (!isFinite(radius)) {
  28505. radius = 1;
  28506. worldCenter.copyFromFloats(0, 0, 0);
  28507. }
  28508. if (createArcRotateCamera) {
  28509. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28510. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28511. arcRotateCamera.wheelPrecision = 100 / radius;
  28512. camera = arcRotateCamera;
  28513. }
  28514. else {
  28515. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28516. freeCamera.setTarget(worldCenter);
  28517. camera = freeCamera;
  28518. }
  28519. camera.minZ = radius * 0.01;
  28520. camera.maxZ = radius * 1000;
  28521. camera.speed = radius * 0.2;
  28522. this.activeCamera = camera;
  28523. var canvas = this.getEngine().getRenderingCanvas();
  28524. if (attachCameraControls && canvas) {
  28525. camera.attachControl(canvas);
  28526. }
  28527. }
  28528. };
  28529. /**
  28530. * Creates a default camera and a default light
  28531. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28532. * @param replace defines if the camera and/or light will replace the existing ones
  28533. * @param attachCameraControls defines if attachControl will be called on the new camera
  28534. */
  28535. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28536. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28537. if (replace === void 0) { replace = false; }
  28538. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28539. this.createDefaultLight(replace);
  28540. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28541. };
  28542. /**
  28543. * Creates a new sky box
  28544. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28545. * @param environmentTexture defines the texture to use as environment texture
  28546. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28547. * @param scale defines the overall scale of the skybox
  28548. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28549. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28550. * @returns a new mesh holding the sky box
  28551. */
  28552. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28553. if (pbr === void 0) { pbr = false; }
  28554. if (scale === void 0) { scale = 1000; }
  28555. if (blur === void 0) { blur = 0; }
  28556. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28557. if (!environmentTexture) {
  28558. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28559. return null;
  28560. }
  28561. if (setGlobalEnvTexture) {
  28562. if (environmentTexture) {
  28563. this.environmentTexture = environmentTexture;
  28564. }
  28565. }
  28566. // Skybox
  28567. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28568. if (pbr) {
  28569. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28570. hdrSkyboxMaterial.backFaceCulling = false;
  28571. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28572. if (hdrSkyboxMaterial.reflectionTexture) {
  28573. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28574. }
  28575. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28576. hdrSkyboxMaterial.disableLighting = true;
  28577. hdrSkyboxMaterial.twoSidedLighting = true;
  28578. hdrSkybox.infiniteDistance = true;
  28579. hdrSkybox.material = hdrSkyboxMaterial;
  28580. }
  28581. else {
  28582. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28583. skyboxMaterial.backFaceCulling = false;
  28584. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28585. if (skyboxMaterial.reflectionTexture) {
  28586. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28587. }
  28588. skyboxMaterial.disableLighting = true;
  28589. hdrSkybox.infiniteDistance = true;
  28590. hdrSkybox.material = skyboxMaterial;
  28591. }
  28592. return hdrSkybox;
  28593. };
  28594. /**
  28595. * Creates a new environment
  28596. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28597. * @param options defines the options you can use to configure the environment
  28598. * @returns the new EnvironmentHelper
  28599. */
  28600. Scene.prototype.createDefaultEnvironment = function (options) {
  28601. if (BABYLON.EnvironmentHelper) {
  28602. return new BABYLON.EnvironmentHelper(options, this);
  28603. }
  28604. return null;
  28605. };
  28606. /**
  28607. * Creates a new VREXperienceHelper
  28608. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28609. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28610. * @returns a new VREXperienceHelper
  28611. */
  28612. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28613. if (webVROptions === void 0) { webVROptions = {}; }
  28614. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28615. };
  28616. // Tags
  28617. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28618. if (tagsQuery === undefined) {
  28619. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28620. return list;
  28621. }
  28622. var listByTags = [];
  28623. forEach = forEach || (function (item) { return; });
  28624. for (var i in list) {
  28625. var item = list[i];
  28626. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28627. listByTags.push(item);
  28628. forEach(item);
  28629. }
  28630. }
  28631. return listByTags;
  28632. };
  28633. /**
  28634. * Get a list of meshes by tags
  28635. * @param tagsQuery defines the tags query to use
  28636. * @param forEach defines a predicate used to filter results
  28637. * @returns an array of Mesh
  28638. */
  28639. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28640. return this._getByTags(this.meshes, tagsQuery, forEach);
  28641. };
  28642. /**
  28643. * Get a list of cameras 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 Camera
  28647. */
  28648. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28649. return this._getByTags(this.cameras, tagsQuery, forEach);
  28650. };
  28651. /**
  28652. * Get a list of lights 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 Light
  28656. */
  28657. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28658. return this._getByTags(this.lights, tagsQuery, forEach);
  28659. };
  28660. /**
  28661. * Get a list of materials 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 Material
  28665. */
  28666. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28667. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28668. };
  28669. /**
  28670. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28671. * This allowed control for front to back rendering or reversly depending of the special needs.
  28672. *
  28673. * @param renderingGroupId The rendering group id corresponding to its index
  28674. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28675. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28676. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28677. */
  28678. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28679. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28680. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28681. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28682. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28683. };
  28684. /**
  28685. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28686. *
  28687. * @param renderingGroupId The rendering group id corresponding to its index
  28688. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28689. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28690. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28691. */
  28692. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28693. if (depth === void 0) { depth = true; }
  28694. if (stencil === void 0) { stencil = true; }
  28695. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28696. };
  28697. /**
  28698. * Will flag all materials as dirty to trigger new shader compilation
  28699. * @param flag defines the flag used to specify which material part must be marked as dirty
  28700. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28701. */
  28702. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28703. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28704. var material = _a[_i];
  28705. if (predicate && !predicate(material)) {
  28706. continue;
  28707. }
  28708. material.markAsDirty(flag);
  28709. }
  28710. };
  28711. /** @hidden */
  28712. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28713. var _this = this;
  28714. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28715. this._activeRequests.push(request);
  28716. request.onCompleteObservable.add(function (request) {
  28717. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28718. });
  28719. return request;
  28720. };
  28721. /** @hidden */
  28722. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28723. var _this = this;
  28724. return new Promise(function (resolve, reject) {
  28725. _this._loadFile(url, function (data) {
  28726. resolve(data);
  28727. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28728. reject(exception);
  28729. });
  28730. });
  28731. };
  28732. // Statics
  28733. Scene._FOGMODE_NONE = 0;
  28734. Scene._FOGMODE_EXP = 1;
  28735. Scene._FOGMODE_EXP2 = 2;
  28736. Scene._FOGMODE_LINEAR = 3;
  28737. Scene._uniqueIdCounter = 0;
  28738. /**
  28739. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28740. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28741. */
  28742. Scene.MinDeltaTime = 1.0;
  28743. /**
  28744. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28745. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28746. */
  28747. Scene.MaxDeltaTime = 1000.0;
  28748. /** The distance in pixel that you have to move to prevent some events */
  28749. Scene.DragMovementThreshold = 10; // in pixels
  28750. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28751. Scene.LongPressDelay = 500; // in milliseconds
  28752. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28753. Scene.DoubleClickDelay = 300; // in milliseconds
  28754. /** If you need to check double click without raising a single click at first click, enable this flag */
  28755. Scene.ExclusiveDoubleClickMode = false;
  28756. return Scene;
  28757. }());
  28758. BABYLON.Scene = Scene;
  28759. })(BABYLON || (BABYLON = {}));
  28760. //# sourceMappingURL=babylon.scene.js.map
  28761. var BABYLON;
  28762. (function (BABYLON) {
  28763. /**
  28764. * Set of assets to keep when moving a scene into an asset container.
  28765. */
  28766. var KeepAssets = /** @class */ (function () {
  28767. function KeepAssets() {
  28768. /**
  28769. * Cameras to keep.
  28770. */
  28771. this.cameras = new Array();
  28772. /**
  28773. * Lights to keep.
  28774. */
  28775. this.lights = new Array();
  28776. /**
  28777. * Meshes to keep.
  28778. */
  28779. this.meshes = new Array();
  28780. /**
  28781. * Skeletons to keep.
  28782. */
  28783. this.skeletons = new Array();
  28784. /**
  28785. * ParticleSystems to keep.
  28786. */
  28787. this.particleSystems = new Array();
  28788. /**
  28789. * Animations to keep.
  28790. */
  28791. this.animations = new Array();
  28792. /**
  28793. * AnimationGroups to keep.
  28794. */
  28795. this.animationGroups = new Array();
  28796. /**
  28797. * MultiMaterials to keep.
  28798. */
  28799. this.multiMaterials = new Array();
  28800. /**
  28801. * Materials to keep.
  28802. */
  28803. this.materials = new Array();
  28804. /**
  28805. * MorphTargetManagers to keep.
  28806. */
  28807. this.morphTargetManagers = new Array();
  28808. /**
  28809. * Geometries to keep.
  28810. */
  28811. this.geometries = new Array();
  28812. /**
  28813. * TransformNodes to keep.
  28814. */
  28815. this.transformNodes = new Array();
  28816. /**
  28817. * LensFlareSystems to keep.
  28818. */
  28819. this.lensFlareSystems = new Array();
  28820. /**
  28821. * ShadowGenerators to keep.
  28822. */
  28823. this.shadowGenerators = new Array();
  28824. /**
  28825. * ActionManagers to keep.
  28826. */
  28827. this.actionManagers = new Array();
  28828. /**
  28829. * Sounds to keep.
  28830. */
  28831. this.sounds = new Array();
  28832. /**
  28833. * Textures to keep.
  28834. */
  28835. this.textures = new Array();
  28836. /**
  28837. * Effect layers to keep.
  28838. */
  28839. this.effectLayers = new Array();
  28840. }
  28841. return KeepAssets;
  28842. }());
  28843. BABYLON.KeepAssets = KeepAssets;
  28844. /**
  28845. * Container with a set of assets that can be added or removed from a scene.
  28846. */
  28847. var AssetContainer = /** @class */ (function () {
  28848. /**
  28849. * Instantiates an AssetContainer.
  28850. * @param scene The scene the AssetContainer belongs to.
  28851. */
  28852. function AssetContainer(scene) {
  28853. // Objects
  28854. /**
  28855. * Cameras populated in the container.
  28856. */
  28857. this.cameras = new Array();
  28858. /**
  28859. * Lights populated in the container.
  28860. */
  28861. this.lights = new Array();
  28862. /**
  28863. * Meshes populated in the container.
  28864. */
  28865. this.meshes = new Array();
  28866. /**
  28867. * Skeletons populated in the container.
  28868. */
  28869. this.skeletons = new Array();
  28870. /**
  28871. * ParticleSystems populated in the container.
  28872. */
  28873. this.particleSystems = new Array();
  28874. /**
  28875. * Animations populated in the container.
  28876. */
  28877. this.animations = new Array();
  28878. /**
  28879. * AnimationGroups populated in the container.
  28880. */
  28881. this.animationGroups = new Array();
  28882. /**
  28883. * MultiMaterials populated in the container.
  28884. */
  28885. this.multiMaterials = new Array();
  28886. /**
  28887. * Materials populated in the container.
  28888. */
  28889. this.materials = new Array();
  28890. /**
  28891. * MorphTargetManagers populated in the container.
  28892. */
  28893. this.morphTargetManagers = new Array();
  28894. /**
  28895. * Geometries populated in the container.
  28896. */
  28897. this.geometries = new Array();
  28898. /**
  28899. * TransformNodes populated in the container.
  28900. */
  28901. this.transformNodes = new Array();
  28902. /**
  28903. * LensFlareSystems populated in the container.
  28904. */
  28905. this.lensFlareSystems = new Array();
  28906. /**
  28907. * ShadowGenerators populated in the container.
  28908. */
  28909. this.shadowGenerators = new Array();
  28910. /**
  28911. * ActionManagers populated in the container.
  28912. */
  28913. this.actionManagers = new Array();
  28914. /**
  28915. * Sounds populated in the container.
  28916. */
  28917. this.sounds = new Array();
  28918. /**
  28919. * Textures populated in the container.
  28920. */
  28921. this.textures = new Array();
  28922. /**
  28923. * Effect layers populated in the container.
  28924. */
  28925. this.effectLayers = new Array();
  28926. this.scene = scene;
  28927. }
  28928. /**
  28929. * Adds all the assets from the container to the scene.
  28930. */
  28931. AssetContainer.prototype.addAllToScene = function () {
  28932. var _this = this;
  28933. this.cameras.forEach(function (o) {
  28934. _this.scene.addCamera(o);
  28935. });
  28936. this.lights.forEach(function (o) {
  28937. _this.scene.addLight(o);
  28938. });
  28939. this.meshes.forEach(function (o) {
  28940. _this.scene.addMesh(o);
  28941. });
  28942. this.skeletons.forEach(function (o) {
  28943. _this.scene.addSkeleton(o);
  28944. });
  28945. this.particleSystems.forEach(function (o) {
  28946. _this.scene.addParticleSystem(o);
  28947. });
  28948. this.animations.forEach(function (o) {
  28949. _this.scene.addAnimation(o);
  28950. });
  28951. this.animationGroups.forEach(function (o) {
  28952. _this.scene.addAnimationGroup(o);
  28953. });
  28954. this.multiMaterials.forEach(function (o) {
  28955. _this.scene.addMultiMaterial(o);
  28956. });
  28957. this.materials.forEach(function (o) {
  28958. _this.scene.addMaterial(o);
  28959. });
  28960. this.morphTargetManagers.forEach(function (o) {
  28961. _this.scene.addMorphTargetManager(o);
  28962. });
  28963. this.geometries.forEach(function (o) {
  28964. _this.scene.addGeometry(o);
  28965. });
  28966. this.transformNodes.forEach(function (o) {
  28967. _this.scene.addTransformNode(o);
  28968. });
  28969. this.lensFlareSystems.forEach(function (o) {
  28970. _this.scene.addLensFlareSystem(o);
  28971. });
  28972. this.actionManagers.forEach(function (o) {
  28973. _this.scene.addActionManager(o);
  28974. });
  28975. this.sounds.forEach(function (o) {
  28976. o.play();
  28977. o.autoplay = true;
  28978. _this.scene.mainSoundTrack.AddSound(o);
  28979. });
  28980. this.textures.forEach(function (o) {
  28981. _this.scene.addTexture(o);
  28982. });
  28983. this.effectLayers.forEach(function (o) {
  28984. _this.scene.addEffectLayer(o);
  28985. });
  28986. };
  28987. /**
  28988. * Removes all the assets in the container from the scene
  28989. */
  28990. AssetContainer.prototype.removeAllFromScene = function () {
  28991. var _this = this;
  28992. this.cameras.forEach(function (o) {
  28993. _this.scene.removeCamera(o);
  28994. });
  28995. this.lights.forEach(function (o) {
  28996. _this.scene.removeLight(o);
  28997. });
  28998. this.meshes.forEach(function (o) {
  28999. _this.scene.removeMesh(o);
  29000. });
  29001. this.skeletons.forEach(function (o) {
  29002. _this.scene.removeSkeleton(o);
  29003. });
  29004. this.particleSystems.forEach(function (o) {
  29005. _this.scene.removeParticleSystem(o);
  29006. });
  29007. this.animations.forEach(function (o) {
  29008. _this.scene.removeAnimation(o);
  29009. });
  29010. this.animationGroups.forEach(function (o) {
  29011. _this.scene.removeAnimationGroup(o);
  29012. });
  29013. this.multiMaterials.forEach(function (o) {
  29014. _this.scene.removeMultiMaterial(o);
  29015. });
  29016. this.materials.forEach(function (o) {
  29017. _this.scene.removeMaterial(o);
  29018. });
  29019. this.morphTargetManagers.forEach(function (o) {
  29020. _this.scene.removeMorphTargetManager(o);
  29021. });
  29022. this.geometries.forEach(function (o) {
  29023. _this.scene.removeGeometry(o);
  29024. });
  29025. this.transformNodes.forEach(function (o) {
  29026. _this.scene.removeTransformNode(o);
  29027. });
  29028. this.lensFlareSystems.forEach(function (o) {
  29029. _this.scene.removeLensFlareSystem(o);
  29030. });
  29031. this.actionManagers.forEach(function (o) {
  29032. _this.scene.removeActionManager(o);
  29033. });
  29034. this.sounds.forEach(function (o) {
  29035. o.stop();
  29036. o.autoplay = false;
  29037. _this.scene.mainSoundTrack.RemoveSound(o);
  29038. });
  29039. this.textures.forEach(function (o) {
  29040. _this.scene.removeTexture(o);
  29041. });
  29042. this.effectLayers.forEach(function (o) {
  29043. _this.scene.removeEffectLayer(o);
  29044. });
  29045. };
  29046. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29047. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29048. var asset = sourceAssets_1[_i];
  29049. var move = true;
  29050. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29051. var keepAsset = keepAssets_1[_a];
  29052. if (asset === keepAsset) {
  29053. move = false;
  29054. break;
  29055. }
  29056. }
  29057. if (move) {
  29058. targetAssets.push(asset);
  29059. }
  29060. }
  29061. };
  29062. /**
  29063. * Removes all the assets contained in the scene and adds them to the container.
  29064. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29065. */
  29066. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29067. if (keepAssets === undefined) {
  29068. keepAssets = new KeepAssets();
  29069. }
  29070. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29071. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29072. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29073. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29074. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29075. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29076. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29077. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29078. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29079. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29080. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29081. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29082. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29083. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29084. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29085. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29086. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29087. this.removeAllFromScene();
  29088. };
  29089. return AssetContainer;
  29090. }());
  29091. BABYLON.AssetContainer = AssetContainer;
  29092. })(BABYLON || (BABYLON = {}));
  29093. //# sourceMappingURL=babylon.assetContainer.js.map
  29094. var BABYLON;
  29095. (function (BABYLON) {
  29096. var Buffer = /** @class */ (function () {
  29097. /**
  29098. * Constructor
  29099. * @param engine the engine
  29100. * @param data the data to use for this buffer
  29101. * @param updatable whether the data is updatable
  29102. * @param stride the stride (optional)
  29103. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29104. * @param instanced whether the buffer is instanced (optional)
  29105. * @param useBytes set to true if the stride in in bytes (optional)
  29106. */
  29107. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29108. if (stride === void 0) { stride = 0; }
  29109. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29110. if (instanced === void 0) { instanced = false; }
  29111. if (useBytes === void 0) { useBytes = false; }
  29112. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29113. this._engine = engine.getScene().getEngine();
  29114. }
  29115. else {
  29116. this._engine = engine;
  29117. }
  29118. this._updatable = updatable;
  29119. this._instanced = instanced;
  29120. this._data = data;
  29121. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29122. if (!postponeInternalCreation) { // by default
  29123. this.create();
  29124. }
  29125. }
  29126. /**
  29127. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29128. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29129. * @param offset defines offset in the buffer (0 by default)
  29130. * @param size defines the size in floats of attributes (position is 3 for instance)
  29131. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29132. * @param instanced defines if the vertex buffer contains indexed data
  29133. * @param useBytes defines if the offset and stride are in bytes
  29134. * @returns the new vertex buffer
  29135. */
  29136. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29137. if (useBytes === void 0) { useBytes = false; }
  29138. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29139. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29140. // a lot of these parameters are ignored as they are overriden by the buffer
  29141. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29142. };
  29143. // Properties
  29144. Buffer.prototype.isUpdatable = function () {
  29145. return this._updatable;
  29146. };
  29147. Buffer.prototype.getData = function () {
  29148. return this._data;
  29149. };
  29150. Buffer.prototype.getBuffer = function () {
  29151. return this._buffer;
  29152. };
  29153. /**
  29154. * Gets the stride in float32 units (i.e. byte stride / 4).
  29155. * May not be an integer if the byte stride is not divisible by 4.
  29156. * DEPRECATED. Use byteStride instead.
  29157. * @returns the stride in float32 units
  29158. */
  29159. Buffer.prototype.getStrideSize = function () {
  29160. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29161. };
  29162. // Methods
  29163. Buffer.prototype.create = function (data) {
  29164. if (data === void 0) { data = null; }
  29165. if (!data && this._buffer) {
  29166. return; // nothing to do
  29167. }
  29168. data = data || this._data;
  29169. if (!data) {
  29170. return;
  29171. }
  29172. if (!this._buffer) { // create buffer
  29173. if (this._updatable) {
  29174. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29175. this._data = data;
  29176. }
  29177. else {
  29178. this._buffer = this._engine.createVertexBuffer(data);
  29179. }
  29180. }
  29181. else if (this._updatable) { // update buffer
  29182. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29183. this._data = data;
  29184. }
  29185. };
  29186. Buffer.prototype._rebuild = function () {
  29187. this._buffer = null;
  29188. this.create(this._data);
  29189. };
  29190. Buffer.prototype.update = function (data) {
  29191. this.create(data);
  29192. };
  29193. /**
  29194. * Updates the data directly.
  29195. * @param data the new data
  29196. * @param offset the new offset
  29197. * @param vertexCount the vertex count (optional)
  29198. * @param useBytes set to true if the offset is in bytes
  29199. */
  29200. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29201. if (useBytes === void 0) { useBytes = false; }
  29202. if (!this._buffer) {
  29203. return;
  29204. }
  29205. if (this._updatable) { // update buffer
  29206. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29207. this._data = null;
  29208. }
  29209. };
  29210. Buffer.prototype.dispose = function () {
  29211. if (!this._buffer) {
  29212. return;
  29213. }
  29214. if (this._engine._releaseBuffer(this._buffer)) {
  29215. this._buffer = null;
  29216. }
  29217. };
  29218. return Buffer;
  29219. }());
  29220. BABYLON.Buffer = Buffer;
  29221. })(BABYLON || (BABYLON = {}));
  29222. //# sourceMappingURL=babylon.buffer.js.map
  29223. var BABYLON;
  29224. (function (BABYLON) {
  29225. var VertexBuffer = /** @class */ (function () {
  29226. /**
  29227. * Constructor
  29228. * @param engine the engine
  29229. * @param data the data to use for this vertex buffer
  29230. * @param kind the vertex buffer kind
  29231. * @param updatable whether the data is updatable
  29232. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29233. * @param stride the stride (optional)
  29234. * @param instanced whether the buffer is instanced (optional)
  29235. * @param offset the offset of the data (optional)
  29236. * @param size the number of components (optional)
  29237. * @param type the type of the component (optional)
  29238. * @param normalized whether the data contains normalized data (optional)
  29239. * @param useBytes set to true if stride and offset are in bytes (optional)
  29240. */
  29241. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29242. if (normalized === void 0) { normalized = false; }
  29243. if (useBytes === void 0) { useBytes = false; }
  29244. if (data instanceof BABYLON.Buffer) {
  29245. this._buffer = data;
  29246. this._ownsBuffer = false;
  29247. }
  29248. else {
  29249. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29250. this._ownsBuffer = true;
  29251. }
  29252. this._kind = kind;
  29253. if (type == undefined) {
  29254. var data_1 = this.getData();
  29255. this.type = VertexBuffer.FLOAT;
  29256. if (data_1 instanceof Int8Array)
  29257. this.type = VertexBuffer.BYTE;
  29258. else if (data_1 instanceof Uint8Array)
  29259. this.type = VertexBuffer.UNSIGNED_BYTE;
  29260. else if (data_1 instanceof Int16Array)
  29261. this.type = VertexBuffer.SHORT;
  29262. else if (data_1 instanceof Uint16Array)
  29263. this.type = VertexBuffer.UNSIGNED_SHORT;
  29264. else if (data_1 instanceof Int32Array)
  29265. this.type = VertexBuffer.INT;
  29266. else if (data_1 instanceof Uint32Array)
  29267. this.type = VertexBuffer.UNSIGNED_INT;
  29268. }
  29269. else {
  29270. this.type = type;
  29271. }
  29272. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29273. if (useBytes) {
  29274. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29275. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29276. this.byteOffset = offset || 0;
  29277. }
  29278. else {
  29279. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29280. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29281. this.byteOffset = (offset || 0) * typeByteLength;
  29282. }
  29283. this.normalized = normalized;
  29284. this._instanced = instanced !== undefined ? instanced : false;
  29285. this._instanceDivisor = instanced ? 1 : 0;
  29286. }
  29287. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29288. /**
  29289. * Gets or sets the instance divisor when in instanced mode
  29290. */
  29291. get: function () {
  29292. return this._instanceDivisor;
  29293. },
  29294. set: function (value) {
  29295. this._instanceDivisor = value;
  29296. if (value == 0) {
  29297. this._instanced = false;
  29298. }
  29299. else {
  29300. this._instanced = true;
  29301. }
  29302. },
  29303. enumerable: true,
  29304. configurable: true
  29305. });
  29306. VertexBuffer.prototype._rebuild = function () {
  29307. if (!this._buffer) {
  29308. return;
  29309. }
  29310. this._buffer._rebuild();
  29311. };
  29312. /**
  29313. * Returns the kind of the VertexBuffer (string).
  29314. */
  29315. VertexBuffer.prototype.getKind = function () {
  29316. return this._kind;
  29317. };
  29318. // Properties
  29319. /**
  29320. * Boolean : is the VertexBuffer updatable ?
  29321. */
  29322. VertexBuffer.prototype.isUpdatable = function () {
  29323. return this._buffer.isUpdatable();
  29324. };
  29325. /**
  29326. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29327. */
  29328. VertexBuffer.prototype.getData = function () {
  29329. return this._buffer.getData();
  29330. };
  29331. /**
  29332. * Returns the WebGLBuffer associated to the VertexBuffer.
  29333. */
  29334. VertexBuffer.prototype.getBuffer = function () {
  29335. return this._buffer.getBuffer();
  29336. };
  29337. /**
  29338. * Returns the stride as a multiple of the type byte length.
  29339. * DEPRECATED. Use byteStride instead.
  29340. */
  29341. VertexBuffer.prototype.getStrideSize = function () {
  29342. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29343. };
  29344. /**
  29345. * Returns the offset as a multiple of the type byte length.
  29346. * DEPRECATED. Use byteOffset instead.
  29347. */
  29348. VertexBuffer.prototype.getOffset = function () {
  29349. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29350. };
  29351. /**
  29352. * Returns the number of components per vertex attribute (integer).
  29353. */
  29354. VertexBuffer.prototype.getSize = function () {
  29355. return this._size;
  29356. };
  29357. /**
  29358. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29359. */
  29360. VertexBuffer.prototype.getIsInstanced = function () {
  29361. return this._instanced;
  29362. };
  29363. /**
  29364. * Returns the instancing divisor, zero for non-instanced (integer).
  29365. */
  29366. VertexBuffer.prototype.getInstanceDivisor = function () {
  29367. return this._instanceDivisor;
  29368. };
  29369. // Methods
  29370. /**
  29371. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29372. * Returns the created WebGLBuffer.
  29373. */
  29374. VertexBuffer.prototype.create = function (data) {
  29375. return this._buffer.create(data);
  29376. };
  29377. /**
  29378. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29379. * This function will create a new buffer if the current one is not updatable
  29380. * Returns the updated WebGLBuffer.
  29381. */
  29382. VertexBuffer.prototype.update = function (data) {
  29383. return this._buffer.update(data);
  29384. };
  29385. /**
  29386. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29387. * Returns the directly updated WebGLBuffer.
  29388. * @param data the new data
  29389. * @param offset the new offset
  29390. * @param useBytes set to true if the offset is in bytes
  29391. */
  29392. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29393. if (useBytes === void 0) { useBytes = false; }
  29394. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29395. };
  29396. /**
  29397. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29398. */
  29399. VertexBuffer.prototype.dispose = function () {
  29400. if (this._ownsBuffer) {
  29401. this._buffer.dispose();
  29402. }
  29403. };
  29404. /**
  29405. * Enumerates each value of this vertex buffer as numbers.
  29406. * @param count the number of values to enumerate
  29407. * @param callback the callback function called for each value
  29408. */
  29409. VertexBuffer.prototype.forEach = function (count, callback) {
  29410. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29411. };
  29412. Object.defineProperty(VertexBuffer, "PositionKind", {
  29413. get: function () {
  29414. return VertexBuffer._PositionKind;
  29415. },
  29416. enumerable: true,
  29417. configurable: true
  29418. });
  29419. Object.defineProperty(VertexBuffer, "NormalKind", {
  29420. get: function () {
  29421. return VertexBuffer._NormalKind;
  29422. },
  29423. enumerable: true,
  29424. configurable: true
  29425. });
  29426. Object.defineProperty(VertexBuffer, "TangentKind", {
  29427. get: function () {
  29428. return VertexBuffer._TangentKind;
  29429. },
  29430. enumerable: true,
  29431. configurable: true
  29432. });
  29433. Object.defineProperty(VertexBuffer, "UVKind", {
  29434. get: function () {
  29435. return VertexBuffer._UVKind;
  29436. },
  29437. enumerable: true,
  29438. configurable: true
  29439. });
  29440. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29441. get: function () {
  29442. return VertexBuffer._UV2Kind;
  29443. },
  29444. enumerable: true,
  29445. configurable: true
  29446. });
  29447. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29448. get: function () {
  29449. return VertexBuffer._UV3Kind;
  29450. },
  29451. enumerable: true,
  29452. configurable: true
  29453. });
  29454. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29455. get: function () {
  29456. return VertexBuffer._UV4Kind;
  29457. },
  29458. enumerable: true,
  29459. configurable: true
  29460. });
  29461. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29462. get: function () {
  29463. return VertexBuffer._UV5Kind;
  29464. },
  29465. enumerable: true,
  29466. configurable: true
  29467. });
  29468. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29469. get: function () {
  29470. return VertexBuffer._UV6Kind;
  29471. },
  29472. enumerable: true,
  29473. configurable: true
  29474. });
  29475. Object.defineProperty(VertexBuffer, "ColorKind", {
  29476. get: function () {
  29477. return VertexBuffer._ColorKind;
  29478. },
  29479. enumerable: true,
  29480. configurable: true
  29481. });
  29482. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29483. get: function () {
  29484. return VertexBuffer._MatricesIndicesKind;
  29485. },
  29486. enumerable: true,
  29487. configurable: true
  29488. });
  29489. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29490. get: function () {
  29491. return VertexBuffer._MatricesWeightsKind;
  29492. },
  29493. enumerable: true,
  29494. configurable: true
  29495. });
  29496. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29497. get: function () {
  29498. return VertexBuffer._MatricesIndicesExtraKind;
  29499. },
  29500. enumerable: true,
  29501. configurable: true
  29502. });
  29503. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29504. get: function () {
  29505. return VertexBuffer._MatricesWeightsExtraKind;
  29506. },
  29507. enumerable: true,
  29508. configurable: true
  29509. });
  29510. /**
  29511. * Deduces the stride given a kind.
  29512. * @param kind The kind string to deduce
  29513. * @returns The deduced stride
  29514. */
  29515. VertexBuffer.DeduceStride = function (kind) {
  29516. switch (kind) {
  29517. case VertexBuffer.UVKind:
  29518. case VertexBuffer.UV2Kind:
  29519. case VertexBuffer.UV3Kind:
  29520. case VertexBuffer.UV4Kind:
  29521. case VertexBuffer.UV5Kind:
  29522. case VertexBuffer.UV6Kind:
  29523. return 2;
  29524. case VertexBuffer.NormalKind:
  29525. case VertexBuffer.PositionKind:
  29526. return 3;
  29527. case VertexBuffer.ColorKind:
  29528. case VertexBuffer.MatricesIndicesKind:
  29529. case VertexBuffer.MatricesIndicesExtraKind:
  29530. case VertexBuffer.MatricesWeightsKind:
  29531. case VertexBuffer.MatricesWeightsExtraKind:
  29532. case VertexBuffer.TangentKind:
  29533. return 4;
  29534. default:
  29535. throw new Error("Invalid kind '" + kind + "'");
  29536. }
  29537. };
  29538. /**
  29539. * Gets the byte length of the given type.
  29540. * @param type the type
  29541. * @returns the number of bytes
  29542. */
  29543. VertexBuffer.GetTypeByteLength = function (type) {
  29544. switch (type) {
  29545. case VertexBuffer.BYTE:
  29546. case VertexBuffer.UNSIGNED_BYTE:
  29547. return 1;
  29548. case VertexBuffer.SHORT:
  29549. case VertexBuffer.UNSIGNED_SHORT:
  29550. return 2;
  29551. case VertexBuffer.INT:
  29552. case VertexBuffer.FLOAT:
  29553. return 4;
  29554. default:
  29555. throw new Error("Invalid type '" + type + "'");
  29556. }
  29557. };
  29558. /**
  29559. * Enumerates each value of the given parameters as numbers.
  29560. * @param data the data to enumerate
  29561. * @param byteOffset the byte offset of the data
  29562. * @param byteStride the byte stride of the data
  29563. * @param componentCount the number of components per element
  29564. * @param componentType the type of the component
  29565. * @param count the total number of components
  29566. * @param normalized whether the data is normalized
  29567. * @param callback the callback function called for each value
  29568. */
  29569. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29570. if (data instanceof Array) {
  29571. var offset = byteOffset / 4;
  29572. var stride = byteStride / 4;
  29573. for (var index = 0; index < count; index += componentCount) {
  29574. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29575. callback(data[offset + componentIndex], index + componentIndex);
  29576. }
  29577. offset += stride;
  29578. }
  29579. }
  29580. else {
  29581. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29582. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29583. for (var index = 0; index < count; index += componentCount) {
  29584. var componentByteOffset = byteOffset;
  29585. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29586. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29587. callback(value, index + componentIndex);
  29588. componentByteOffset += componentByteLength;
  29589. }
  29590. byteOffset += byteStride;
  29591. }
  29592. }
  29593. };
  29594. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29595. switch (type) {
  29596. case VertexBuffer.BYTE: {
  29597. var value = dataView.getInt8(byteOffset);
  29598. if (normalized) {
  29599. value = (value + 0.5) / 127.5;
  29600. }
  29601. return value;
  29602. }
  29603. case VertexBuffer.UNSIGNED_BYTE: {
  29604. var value = dataView.getUint8(byteOffset);
  29605. if (normalized) {
  29606. value = value / 255;
  29607. }
  29608. return value;
  29609. }
  29610. case VertexBuffer.SHORT: {
  29611. var value = dataView.getInt16(byteOffset, true);
  29612. if (normalized) {
  29613. value = (value + 0.5) / 16383.5;
  29614. }
  29615. return value;
  29616. }
  29617. case VertexBuffer.UNSIGNED_SHORT: {
  29618. var value = dataView.getUint16(byteOffset, true);
  29619. if (normalized) {
  29620. value = value / 65535;
  29621. }
  29622. return value;
  29623. }
  29624. case VertexBuffer.FLOAT: {
  29625. return dataView.getFloat32(byteOffset, true);
  29626. }
  29627. default: {
  29628. throw new Error("Invalid component type " + type);
  29629. }
  29630. }
  29631. };
  29632. /**
  29633. * The byte type.
  29634. */
  29635. VertexBuffer.BYTE = 5120;
  29636. /**
  29637. * The unsigned byte type.
  29638. */
  29639. VertexBuffer.UNSIGNED_BYTE = 5121;
  29640. /**
  29641. * The short type.
  29642. */
  29643. VertexBuffer.SHORT = 5122;
  29644. /**
  29645. * The unsigned short type.
  29646. */
  29647. VertexBuffer.UNSIGNED_SHORT = 5123;
  29648. /**
  29649. * The integer type.
  29650. */
  29651. VertexBuffer.INT = 5124;
  29652. /**
  29653. * The unsigned integer type.
  29654. */
  29655. VertexBuffer.UNSIGNED_INT = 5125;
  29656. /**
  29657. * The float type.
  29658. */
  29659. VertexBuffer.FLOAT = 5126;
  29660. // Enums
  29661. VertexBuffer._PositionKind = "position";
  29662. VertexBuffer._NormalKind = "normal";
  29663. VertexBuffer._TangentKind = "tangent";
  29664. VertexBuffer._UVKind = "uv";
  29665. VertexBuffer._UV2Kind = "uv2";
  29666. VertexBuffer._UV3Kind = "uv3";
  29667. VertexBuffer._UV4Kind = "uv4";
  29668. VertexBuffer._UV5Kind = "uv5";
  29669. VertexBuffer._UV6Kind = "uv6";
  29670. VertexBuffer._ColorKind = "color";
  29671. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29672. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29673. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29674. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29675. return VertexBuffer;
  29676. }());
  29677. BABYLON.VertexBuffer = VertexBuffer;
  29678. })(BABYLON || (BABYLON = {}));
  29679. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29680. var BABYLON;
  29681. (function (BABYLON) {
  29682. /**
  29683. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29684. */
  29685. var DummyInternalTextureTracker = /** @class */ (function () {
  29686. function DummyInternalTextureTracker() {
  29687. /**
  29688. * Gets or set the previous tracker in the list
  29689. */
  29690. this.previous = null;
  29691. /**
  29692. * Gets or set the next tracker in the list
  29693. */
  29694. this.next = null;
  29695. }
  29696. return DummyInternalTextureTracker;
  29697. }());
  29698. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29699. })(BABYLON || (BABYLON = {}));
  29700. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29701. var BABYLON;
  29702. (function (BABYLON) {
  29703. /**
  29704. * Class used to store data associated with WebGL texture data for the engine
  29705. * This class should not be used directly
  29706. */
  29707. var InternalTexture = /** @class */ (function () {
  29708. /**
  29709. * Creates a new InternalTexture
  29710. * @param engine defines the engine to use
  29711. * @param dataSource defines the type of data that will be used
  29712. */
  29713. function InternalTexture(engine, dataSource) {
  29714. /**
  29715. * Observable called when the texture is loaded
  29716. */
  29717. this.onLoadedObservable = new BABYLON.Observable();
  29718. /**
  29719. * Gets or set the previous tracker in the list
  29720. */
  29721. this.previous = null;
  29722. /**
  29723. * Gets or set the next tracker in the list
  29724. */
  29725. this.next = null;
  29726. // Private
  29727. /** @hidden */
  29728. this._initialSlot = -1;
  29729. /** @hidden */
  29730. this._designatedSlot = -1;
  29731. /** @hidden */
  29732. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29733. /** @hidden */
  29734. this._comparisonFunction = 0;
  29735. /** @hidden */
  29736. this._references = 1;
  29737. this._engine = engine;
  29738. this._dataSource = dataSource;
  29739. this._webGLTexture = engine._createTexture();
  29740. }
  29741. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29742. /**
  29743. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29744. */
  29745. get: function () {
  29746. return this._dataSource;
  29747. },
  29748. enumerable: true,
  29749. configurable: true
  29750. });
  29751. /**
  29752. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29753. */
  29754. InternalTexture.prototype.incrementReferences = function () {
  29755. this._references++;
  29756. };
  29757. /**
  29758. * Change the size of the texture (not the size of the content)
  29759. * @param width defines the new width
  29760. * @param height defines the new height
  29761. * @param depth defines the new depth (1 by default)
  29762. */
  29763. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29764. if (depth === void 0) { depth = 1; }
  29765. this.width = width;
  29766. this.height = height;
  29767. this.depth = depth;
  29768. this.baseWidth = width;
  29769. this.baseHeight = height;
  29770. this.baseDepth = depth;
  29771. this._size = width * height * depth;
  29772. };
  29773. /** @hidden */
  29774. InternalTexture.prototype._rebuild = function () {
  29775. var _this = this;
  29776. var proxy;
  29777. this.isReady = false;
  29778. this._cachedCoordinatesMode = null;
  29779. this._cachedWrapU = null;
  29780. this._cachedWrapV = null;
  29781. this._cachedAnisotropicFilteringLevel = null;
  29782. switch (this._dataSource) {
  29783. case InternalTexture.DATASOURCE_TEMP:
  29784. return;
  29785. case InternalTexture.DATASOURCE_URL:
  29786. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29787. _this.isReady = true;
  29788. }, null, this._buffer, undefined, this.format);
  29789. proxy._swapAndDie(this);
  29790. return;
  29791. case InternalTexture.DATASOURCE_RAW:
  29792. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29793. proxy._swapAndDie(this);
  29794. this.isReady = true;
  29795. return;
  29796. case InternalTexture.DATASOURCE_RAW3D:
  29797. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29798. proxy._swapAndDie(this);
  29799. this.isReady = true;
  29800. return;
  29801. case InternalTexture.DATASOURCE_DYNAMIC:
  29802. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29803. proxy._swapAndDie(this);
  29804. // The engine will make sure to update content so no need to flag it as isReady = true
  29805. return;
  29806. case InternalTexture.DATASOURCE_RENDERTARGET:
  29807. var options = new BABYLON.RenderTargetCreationOptions();
  29808. options.generateDepthBuffer = this._generateDepthBuffer;
  29809. options.generateMipMaps = this.generateMipMaps;
  29810. options.generateStencilBuffer = this._generateStencilBuffer;
  29811. options.samplingMode = this.samplingMode;
  29812. options.type = this.type;
  29813. if (this.isCube) {
  29814. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29815. }
  29816. else {
  29817. var size = {
  29818. width: this.width,
  29819. height: this.height
  29820. };
  29821. proxy = this._engine.createRenderTargetTexture(size, options);
  29822. }
  29823. proxy._swapAndDie(this);
  29824. this.isReady = true;
  29825. return;
  29826. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29827. var depthTextureOptions = {
  29828. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29829. comparisonFunction: this._comparisonFunction,
  29830. generateStencil: this._generateStencilBuffer,
  29831. isCube: this.isCube
  29832. };
  29833. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29834. proxy._swapAndDie(this);
  29835. this.isReady = true;
  29836. return;
  29837. case InternalTexture.DATASOURCE_CUBE:
  29838. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29839. _this.isReady = true;
  29840. }, null, this.format, this._extension);
  29841. proxy._swapAndDie(this);
  29842. return;
  29843. case InternalTexture.DATASOURCE_CUBERAW:
  29844. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29845. proxy._swapAndDie(this);
  29846. this.isReady = true;
  29847. return;
  29848. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29849. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29850. if (proxy) {
  29851. proxy._swapAndDie(_this);
  29852. }
  29853. _this.isReady = true;
  29854. }, null, this.format, this._extension);
  29855. return;
  29856. }
  29857. };
  29858. InternalTexture.prototype._swapAndDie = function (target) {
  29859. target._webGLTexture = this._webGLTexture;
  29860. if (this._framebuffer) {
  29861. target._framebuffer = this._framebuffer;
  29862. }
  29863. if (this._depthStencilBuffer) {
  29864. target._depthStencilBuffer = this._depthStencilBuffer;
  29865. }
  29866. if (this._lodTextureHigh) {
  29867. if (target._lodTextureHigh) {
  29868. target._lodTextureHigh.dispose();
  29869. }
  29870. target._lodTextureHigh = this._lodTextureHigh;
  29871. }
  29872. if (this._lodTextureMid) {
  29873. if (target._lodTextureMid) {
  29874. target._lodTextureMid.dispose();
  29875. }
  29876. target._lodTextureMid = this._lodTextureMid;
  29877. }
  29878. if (this._lodTextureLow) {
  29879. if (target._lodTextureLow) {
  29880. target._lodTextureLow.dispose();
  29881. }
  29882. target._lodTextureLow = this._lodTextureLow;
  29883. }
  29884. var cache = this._engine.getLoadedTexturesCache();
  29885. var index = cache.indexOf(this);
  29886. if (index !== -1) {
  29887. cache.splice(index, 1);
  29888. }
  29889. };
  29890. /**
  29891. * Dispose the current allocated resources
  29892. */
  29893. InternalTexture.prototype.dispose = function () {
  29894. if (!this._webGLTexture) {
  29895. return;
  29896. }
  29897. this._references--;
  29898. if (this._references === 0) {
  29899. this._engine._releaseTexture(this);
  29900. this._webGLTexture = null;
  29901. this.previous = null;
  29902. this.next = null;
  29903. }
  29904. };
  29905. /**
  29906. * The source of the texture data is unknown
  29907. */
  29908. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29909. /**
  29910. * Texture data comes from an URL
  29911. */
  29912. InternalTexture.DATASOURCE_URL = 1;
  29913. /**
  29914. * Texture data is only used for temporary storage
  29915. */
  29916. InternalTexture.DATASOURCE_TEMP = 2;
  29917. /**
  29918. * Texture data comes from raw data (ArrayBuffer)
  29919. */
  29920. InternalTexture.DATASOURCE_RAW = 3;
  29921. /**
  29922. * Texture content is dynamic (video or dynamic texture)
  29923. */
  29924. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29925. /**
  29926. * Texture content is generated by rendering to it
  29927. */
  29928. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29929. /**
  29930. * Texture content is part of a multi render target process
  29931. */
  29932. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29933. /**
  29934. * Texture data comes from a cube data file
  29935. */
  29936. InternalTexture.DATASOURCE_CUBE = 7;
  29937. /**
  29938. * Texture data comes from a raw cube data
  29939. */
  29940. InternalTexture.DATASOURCE_CUBERAW = 8;
  29941. /**
  29942. * Texture data come from a prefiltered cube data file
  29943. */
  29944. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29945. /**
  29946. * Texture content is raw 3D data
  29947. */
  29948. InternalTexture.DATASOURCE_RAW3D = 10;
  29949. /**
  29950. * Texture content is a depth texture
  29951. */
  29952. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29953. return InternalTexture;
  29954. }());
  29955. BABYLON.InternalTexture = InternalTexture;
  29956. })(BABYLON || (BABYLON = {}));
  29957. //# sourceMappingURL=babylon.internalTexture.js.map
  29958. var BABYLON;
  29959. (function (BABYLON) {
  29960. var BaseTexture = /** @class */ (function () {
  29961. function BaseTexture(scene) {
  29962. this._hasAlpha = false;
  29963. this.getAlphaFromRGB = false;
  29964. this.level = 1;
  29965. this.coordinatesIndex = 0;
  29966. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29967. /**
  29968. * | Value | Type | Description |
  29969. * | ----- | ------------------ | ----------- |
  29970. * | 0 | CLAMP_ADDRESSMODE | |
  29971. * | 1 | WRAP_ADDRESSMODE | |
  29972. * | 2 | MIRROR_ADDRESSMODE | |
  29973. */
  29974. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29975. /**
  29976. * | Value | Type | Description |
  29977. * | ----- | ------------------ | ----------- |
  29978. * | 0 | CLAMP_ADDRESSMODE | |
  29979. * | 1 | WRAP_ADDRESSMODE | |
  29980. * | 2 | MIRROR_ADDRESSMODE | |
  29981. */
  29982. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29983. /**
  29984. * | Value | Type | Description |
  29985. * | ----- | ------------------ | ----------- |
  29986. * | 0 | CLAMP_ADDRESSMODE | |
  29987. * | 1 | WRAP_ADDRESSMODE | |
  29988. * | 2 | MIRROR_ADDRESSMODE | |
  29989. */
  29990. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29991. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29992. this.isCube = false;
  29993. this.is3D = false;
  29994. this.gammaSpace = true;
  29995. this.invertZ = false;
  29996. this.lodLevelInAlpha = false;
  29997. this.lodGenerationOffset = 0.0;
  29998. this.lodGenerationScale = 0.8;
  29999. this.isRenderTarget = false;
  30000. this.animations = new Array();
  30001. /**
  30002. * An event triggered when the texture is disposed.
  30003. */
  30004. this.onDisposeObservable = new BABYLON.Observable();
  30005. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30006. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30007. if (this._scene) {
  30008. this._scene.textures.push(this);
  30009. }
  30010. this._uid = null;
  30011. }
  30012. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30013. get: function () {
  30014. return this._hasAlpha;
  30015. },
  30016. set: function (value) {
  30017. if (this._hasAlpha === value) {
  30018. return;
  30019. }
  30020. this._hasAlpha = value;
  30021. if (this._scene) {
  30022. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30023. }
  30024. },
  30025. enumerable: true,
  30026. configurable: true
  30027. });
  30028. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30029. get: function () {
  30030. return this._coordinatesMode;
  30031. },
  30032. /**
  30033. * How a texture is mapped.
  30034. *
  30035. * | Value | Type | Description |
  30036. * | ----- | ----------------------------------- | ----------- |
  30037. * | 0 | EXPLICIT_MODE | |
  30038. * | 1 | SPHERICAL_MODE | |
  30039. * | 2 | PLANAR_MODE | |
  30040. * | 3 | CUBIC_MODE | |
  30041. * | 4 | PROJECTION_MODE | |
  30042. * | 5 | SKYBOX_MODE | |
  30043. * | 6 | INVCUBIC_MODE | |
  30044. * | 7 | EQUIRECTANGULAR_MODE | |
  30045. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30046. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30047. */
  30048. set: function (value) {
  30049. if (this._coordinatesMode === value) {
  30050. return;
  30051. }
  30052. this._coordinatesMode = value;
  30053. if (this._scene) {
  30054. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30055. }
  30056. },
  30057. enumerable: true,
  30058. configurable: true
  30059. });
  30060. Object.defineProperty(BaseTexture.prototype, "uid", {
  30061. get: function () {
  30062. if (!this._uid) {
  30063. this._uid = BABYLON.Tools.RandomId();
  30064. }
  30065. return this._uid;
  30066. },
  30067. enumerable: true,
  30068. configurable: true
  30069. });
  30070. BaseTexture.prototype.toString = function () {
  30071. return this.name;
  30072. };
  30073. BaseTexture.prototype.getClassName = function () {
  30074. return "BaseTexture";
  30075. };
  30076. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30077. set: function (callback) {
  30078. if (this._onDisposeObserver) {
  30079. this.onDisposeObservable.remove(this._onDisposeObserver);
  30080. }
  30081. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30082. },
  30083. enumerable: true,
  30084. configurable: true
  30085. });
  30086. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30087. get: function () {
  30088. return true;
  30089. },
  30090. enumerable: true,
  30091. configurable: true
  30092. });
  30093. BaseTexture.prototype.getScene = function () {
  30094. return this._scene;
  30095. };
  30096. BaseTexture.prototype.getTextureMatrix = function () {
  30097. return BABYLON.Matrix.IdentityReadOnly;
  30098. };
  30099. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30100. return BABYLON.Matrix.IdentityReadOnly;
  30101. };
  30102. BaseTexture.prototype.getInternalTexture = function () {
  30103. return this._texture;
  30104. };
  30105. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30106. return !this.isBlocking || this.isReady();
  30107. };
  30108. BaseTexture.prototype.isReady = function () {
  30109. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30110. this.delayLoad();
  30111. return false;
  30112. }
  30113. if (this._texture) {
  30114. return this._texture.isReady;
  30115. }
  30116. return false;
  30117. };
  30118. BaseTexture.prototype.getSize = function () {
  30119. if (this._texture && this._texture.width) {
  30120. return new BABYLON.Size(this._texture.width, this._texture.height);
  30121. }
  30122. if (this._texture && this._texture._size) {
  30123. return new BABYLON.Size(this._texture._size, this._texture._size);
  30124. }
  30125. return BABYLON.Size.Zero();
  30126. };
  30127. BaseTexture.prototype.getBaseSize = function () {
  30128. if (!this.isReady() || !this._texture)
  30129. return BABYLON.Size.Zero();
  30130. if (this._texture._size) {
  30131. return new BABYLON.Size(this._texture._size, this._texture._size);
  30132. }
  30133. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30134. };
  30135. BaseTexture.prototype.scale = function (ratio) {
  30136. };
  30137. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30138. get: function () {
  30139. return false;
  30140. },
  30141. enumerable: true,
  30142. configurable: true
  30143. });
  30144. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30145. if (!this._scene) {
  30146. return null;
  30147. }
  30148. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30149. for (var index = 0; index < texturesCache.length; index++) {
  30150. var texturesCacheEntry = texturesCache[index];
  30151. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30152. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30153. texturesCacheEntry.incrementReferences();
  30154. return texturesCacheEntry;
  30155. }
  30156. }
  30157. }
  30158. return null;
  30159. };
  30160. BaseTexture.prototype._rebuild = function () {
  30161. };
  30162. BaseTexture.prototype.delayLoad = function () {
  30163. };
  30164. BaseTexture.prototype.clone = function () {
  30165. return null;
  30166. };
  30167. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30168. get: function () {
  30169. if (!this._texture) {
  30170. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30171. }
  30172. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30173. },
  30174. enumerable: true,
  30175. configurable: true
  30176. });
  30177. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30178. get: function () {
  30179. if (!this._texture) {
  30180. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30181. }
  30182. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30183. },
  30184. enumerable: true,
  30185. configurable: true
  30186. });
  30187. BaseTexture.prototype.readPixels = function (faceIndex) {
  30188. if (faceIndex === void 0) { faceIndex = 0; }
  30189. if (!this._texture) {
  30190. return null;
  30191. }
  30192. var size = this.getSize();
  30193. var scene = this.getScene();
  30194. if (!scene) {
  30195. return null;
  30196. }
  30197. var engine = scene.getEngine();
  30198. if (this._texture.isCube) {
  30199. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30200. }
  30201. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30202. };
  30203. BaseTexture.prototype.releaseInternalTexture = function () {
  30204. if (this._texture) {
  30205. this._texture.dispose();
  30206. this._texture = null;
  30207. }
  30208. };
  30209. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30210. get: function () {
  30211. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30212. return null;
  30213. }
  30214. if (!this._texture._sphericalPolynomial) {
  30215. this._texture._sphericalPolynomial =
  30216. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30217. }
  30218. return this._texture._sphericalPolynomial;
  30219. },
  30220. set: function (value) {
  30221. if (this._texture) {
  30222. this._texture._sphericalPolynomial = value;
  30223. }
  30224. },
  30225. enumerable: true,
  30226. configurable: true
  30227. });
  30228. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30229. get: function () {
  30230. if (this._texture) {
  30231. return this._texture._lodTextureHigh;
  30232. }
  30233. return null;
  30234. },
  30235. enumerable: true,
  30236. configurable: true
  30237. });
  30238. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30239. get: function () {
  30240. if (this._texture) {
  30241. return this._texture._lodTextureMid;
  30242. }
  30243. return null;
  30244. },
  30245. enumerable: true,
  30246. configurable: true
  30247. });
  30248. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30249. get: function () {
  30250. if (this._texture) {
  30251. return this._texture._lodTextureLow;
  30252. }
  30253. return null;
  30254. },
  30255. enumerable: true,
  30256. configurable: true
  30257. });
  30258. BaseTexture.prototype.dispose = function () {
  30259. if (!this._scene) {
  30260. return;
  30261. }
  30262. // Animations
  30263. this._scene.stopAnimation(this);
  30264. // Remove from scene
  30265. this._scene._removePendingData(this);
  30266. var index = this._scene.textures.indexOf(this);
  30267. if (index >= 0) {
  30268. this._scene.textures.splice(index, 1);
  30269. }
  30270. if (this._texture === undefined) {
  30271. return;
  30272. }
  30273. // Release
  30274. this.releaseInternalTexture();
  30275. // Callback
  30276. this.onDisposeObservable.notifyObservers(this);
  30277. this.onDisposeObservable.clear();
  30278. };
  30279. BaseTexture.prototype.serialize = function () {
  30280. if (!this.name) {
  30281. return null;
  30282. }
  30283. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30284. // Animations
  30285. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30286. return serializationObject;
  30287. };
  30288. BaseTexture.WhenAllReady = function (textures, callback) {
  30289. var numRemaining = textures.length;
  30290. if (numRemaining === 0) {
  30291. callback();
  30292. return;
  30293. }
  30294. var _loop_1 = function () {
  30295. texture = textures[i];
  30296. if (texture.isReady()) {
  30297. if (--numRemaining === 0) {
  30298. callback();
  30299. }
  30300. }
  30301. else {
  30302. onLoadObservable = texture.onLoadObservable;
  30303. var onLoadCallback_1 = function () {
  30304. onLoadObservable.removeCallback(onLoadCallback_1);
  30305. if (--numRemaining === 0) {
  30306. callback();
  30307. }
  30308. };
  30309. onLoadObservable.add(onLoadCallback_1);
  30310. }
  30311. };
  30312. var texture, onLoadObservable;
  30313. for (var i = 0; i < textures.length; i++) {
  30314. _loop_1();
  30315. }
  30316. };
  30317. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30318. __decorate([
  30319. BABYLON.serialize()
  30320. ], BaseTexture.prototype, "name", void 0);
  30321. __decorate([
  30322. BABYLON.serialize("hasAlpha")
  30323. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30324. __decorate([
  30325. BABYLON.serialize()
  30326. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30327. __decorate([
  30328. BABYLON.serialize()
  30329. ], BaseTexture.prototype, "level", void 0);
  30330. __decorate([
  30331. BABYLON.serialize()
  30332. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30333. __decorate([
  30334. BABYLON.serialize("coordinatesMode")
  30335. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30336. __decorate([
  30337. BABYLON.serialize()
  30338. ], BaseTexture.prototype, "wrapU", void 0);
  30339. __decorate([
  30340. BABYLON.serialize()
  30341. ], BaseTexture.prototype, "wrapV", void 0);
  30342. __decorate([
  30343. BABYLON.serialize()
  30344. ], BaseTexture.prototype, "wrapR", void 0);
  30345. __decorate([
  30346. BABYLON.serialize()
  30347. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30348. __decorate([
  30349. BABYLON.serialize()
  30350. ], BaseTexture.prototype, "isCube", void 0);
  30351. __decorate([
  30352. BABYLON.serialize()
  30353. ], BaseTexture.prototype, "is3D", void 0);
  30354. __decorate([
  30355. BABYLON.serialize()
  30356. ], BaseTexture.prototype, "gammaSpace", void 0);
  30357. __decorate([
  30358. BABYLON.serialize()
  30359. ], BaseTexture.prototype, "invertZ", void 0);
  30360. __decorate([
  30361. BABYLON.serialize()
  30362. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30363. __decorate([
  30364. BABYLON.serialize()
  30365. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30366. __decorate([
  30367. BABYLON.serialize()
  30368. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30369. __decorate([
  30370. BABYLON.serialize()
  30371. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30372. return BaseTexture;
  30373. }());
  30374. BABYLON.BaseTexture = BaseTexture;
  30375. })(BABYLON || (BABYLON = {}));
  30376. //# sourceMappingURL=babylon.baseTexture.js.map
  30377. var BABYLON;
  30378. (function (BABYLON) {
  30379. var Texture = /** @class */ (function (_super) {
  30380. __extends(Texture, _super);
  30381. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30382. if (noMipmap === void 0) { noMipmap = false; }
  30383. if (invertY === void 0) { invertY = true; }
  30384. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30385. if (onLoad === void 0) { onLoad = null; }
  30386. if (onError === void 0) { onError = null; }
  30387. if (buffer === void 0) { buffer = null; }
  30388. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30389. var _this = _super.call(this, scene) || this;
  30390. _this.uOffset = 0;
  30391. _this.vOffset = 0;
  30392. _this.uScale = 1.0;
  30393. _this.vScale = 1.0;
  30394. _this.uAng = 0;
  30395. _this.vAng = 0;
  30396. _this.wAng = 0;
  30397. _this._isBlocking = true;
  30398. _this.name = url || "";
  30399. _this.url = url;
  30400. _this._noMipmap = noMipmap;
  30401. _this._invertY = invertY;
  30402. _this._samplingMode = samplingMode;
  30403. _this._buffer = buffer;
  30404. _this._deleteBuffer = deleteBuffer;
  30405. if (format) {
  30406. _this._format = format;
  30407. }
  30408. scene = _this.getScene();
  30409. if (!scene) {
  30410. return _this;
  30411. }
  30412. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30413. var load = function () {
  30414. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30415. _this.onLoadObservable.notifyObservers(_this);
  30416. }
  30417. if (onLoad) {
  30418. onLoad();
  30419. }
  30420. if (!_this.isBlocking && scene) {
  30421. scene.resetCachedMaterial();
  30422. }
  30423. };
  30424. if (!_this.url) {
  30425. _this._delayedOnLoad = load;
  30426. _this._delayedOnError = onError;
  30427. return _this;
  30428. }
  30429. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30430. if (!_this._texture) {
  30431. if (!scene.useDelayedTextureLoading) {
  30432. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30433. if (deleteBuffer) {
  30434. delete _this._buffer;
  30435. }
  30436. }
  30437. else {
  30438. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30439. _this._delayedOnLoad = load;
  30440. _this._delayedOnError = onError;
  30441. }
  30442. }
  30443. else {
  30444. if (_this._texture.isReady) {
  30445. BABYLON.Tools.SetImmediate(function () { return load(); });
  30446. }
  30447. else {
  30448. _this._texture.onLoadedObservable.add(load);
  30449. }
  30450. }
  30451. return _this;
  30452. }
  30453. Object.defineProperty(Texture.prototype, "noMipmap", {
  30454. get: function () {
  30455. return this._noMipmap;
  30456. },
  30457. enumerable: true,
  30458. configurable: true
  30459. });
  30460. Object.defineProperty(Texture.prototype, "isBlocking", {
  30461. get: function () {
  30462. return this._isBlocking;
  30463. },
  30464. set: function (value) {
  30465. this._isBlocking = value;
  30466. },
  30467. enumerable: true,
  30468. configurable: true
  30469. });
  30470. Object.defineProperty(Texture.prototype, "samplingMode", {
  30471. get: function () {
  30472. return this._samplingMode;
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. Texture.prototype.updateURL = function (url) {
  30478. this.url = url;
  30479. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30480. this.delayLoad();
  30481. };
  30482. Texture.prototype.delayLoad = function () {
  30483. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30484. return;
  30485. }
  30486. var scene = this.getScene();
  30487. if (!scene) {
  30488. return;
  30489. }
  30490. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30491. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30492. if (!this._texture) {
  30493. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30494. if (this._deleteBuffer) {
  30495. delete this._buffer;
  30496. }
  30497. }
  30498. else {
  30499. if (this._delayedOnLoad) {
  30500. if (this._texture.isReady) {
  30501. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30502. }
  30503. else {
  30504. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30505. }
  30506. }
  30507. }
  30508. this._delayedOnLoad = null;
  30509. this._delayedOnError = null;
  30510. };
  30511. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30512. if (!this._texture) {
  30513. return;
  30514. }
  30515. var scene = this.getScene();
  30516. if (!scene) {
  30517. return;
  30518. }
  30519. this._samplingMode = samplingMode;
  30520. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30521. };
  30522. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30523. x *= this.uScale;
  30524. y *= this.vScale;
  30525. x -= 0.5 * this.uScale;
  30526. y -= 0.5 * this.vScale;
  30527. z -= 0.5;
  30528. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30529. t.x += 0.5 * this.uScale + this.uOffset;
  30530. t.y += 0.5 * this.vScale + this.vOffset;
  30531. t.z += 0.5;
  30532. };
  30533. Texture.prototype.getTextureMatrix = function () {
  30534. var _this = this;
  30535. if (this.uOffset === this._cachedUOffset &&
  30536. this.vOffset === this._cachedVOffset &&
  30537. this.uScale === this._cachedUScale &&
  30538. this.vScale === this._cachedVScale &&
  30539. this.uAng === this._cachedUAng &&
  30540. this.vAng === this._cachedVAng &&
  30541. this.wAng === this._cachedWAng) {
  30542. return this._cachedTextureMatrix;
  30543. }
  30544. this._cachedUOffset = this.uOffset;
  30545. this._cachedVOffset = this.vOffset;
  30546. this._cachedUScale = this.uScale;
  30547. this._cachedVScale = this.vScale;
  30548. this._cachedUAng = this.uAng;
  30549. this._cachedVAng = this.vAng;
  30550. this._cachedWAng = this.wAng;
  30551. if (!this._cachedTextureMatrix) {
  30552. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30553. this._rowGenerationMatrix = new BABYLON.Matrix();
  30554. this._t0 = BABYLON.Vector3.Zero();
  30555. this._t1 = BABYLON.Vector3.Zero();
  30556. this._t2 = BABYLON.Vector3.Zero();
  30557. }
  30558. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30559. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30560. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30561. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30562. this._t1.subtractInPlace(this._t0);
  30563. this._t2.subtractInPlace(this._t0);
  30564. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30565. this._cachedTextureMatrix.m[0] = this._t1.x;
  30566. this._cachedTextureMatrix.m[1] = this._t1.y;
  30567. this._cachedTextureMatrix.m[2] = this._t1.z;
  30568. this._cachedTextureMatrix.m[4] = this._t2.x;
  30569. this._cachedTextureMatrix.m[5] = this._t2.y;
  30570. this._cachedTextureMatrix.m[6] = this._t2.z;
  30571. this._cachedTextureMatrix.m[8] = this._t0.x;
  30572. this._cachedTextureMatrix.m[9] = this._t0.y;
  30573. this._cachedTextureMatrix.m[10] = this._t0.z;
  30574. var scene = this.getScene();
  30575. if (!scene) {
  30576. return this._cachedTextureMatrix;
  30577. }
  30578. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30579. return mat.hasTexture(_this);
  30580. });
  30581. return this._cachedTextureMatrix;
  30582. };
  30583. Texture.prototype.getReflectionTextureMatrix = function () {
  30584. var _this = this;
  30585. var scene = this.getScene();
  30586. if (!scene) {
  30587. return this._cachedTextureMatrix;
  30588. }
  30589. if (this.uOffset === this._cachedUOffset &&
  30590. this.vOffset === this._cachedVOffset &&
  30591. this.uScale === this._cachedUScale &&
  30592. this.vScale === this._cachedVScale &&
  30593. this.coordinatesMode === this._cachedCoordinatesMode) {
  30594. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30595. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30596. return this._cachedTextureMatrix;
  30597. }
  30598. }
  30599. else {
  30600. return this._cachedTextureMatrix;
  30601. }
  30602. }
  30603. if (!this._cachedTextureMatrix) {
  30604. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30605. }
  30606. if (!this._projectionModeMatrix) {
  30607. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30608. }
  30609. this._cachedUOffset = this.uOffset;
  30610. this._cachedVOffset = this.vOffset;
  30611. this._cachedUScale = this.uScale;
  30612. this._cachedVScale = this.vScale;
  30613. this._cachedCoordinatesMode = this.coordinatesMode;
  30614. switch (this.coordinatesMode) {
  30615. case Texture.PLANAR_MODE:
  30616. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30617. this._cachedTextureMatrix[0] = this.uScale;
  30618. this._cachedTextureMatrix[5] = this.vScale;
  30619. this._cachedTextureMatrix[12] = this.uOffset;
  30620. this._cachedTextureMatrix[13] = this.vOffset;
  30621. break;
  30622. case Texture.PROJECTION_MODE:
  30623. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30624. this._projectionModeMatrix.m[0] = 0.5;
  30625. this._projectionModeMatrix.m[5] = -0.5;
  30626. this._projectionModeMatrix.m[10] = 0.0;
  30627. this._projectionModeMatrix.m[12] = 0.5;
  30628. this._projectionModeMatrix.m[13] = 0.5;
  30629. this._projectionModeMatrix.m[14] = 1.0;
  30630. this._projectionModeMatrix.m[15] = 1.0;
  30631. var projectionMatrix = scene.getProjectionMatrix();
  30632. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30633. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30634. break;
  30635. default:
  30636. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30637. break;
  30638. }
  30639. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30640. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30641. });
  30642. return this._cachedTextureMatrix;
  30643. };
  30644. Texture.prototype.clone = function () {
  30645. var _this = this;
  30646. return BABYLON.SerializationHelper.Clone(function () {
  30647. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30648. }, this);
  30649. };
  30650. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30651. get: function () {
  30652. if (!this._onLoadObservable) {
  30653. this._onLoadObservable = new BABYLON.Observable();
  30654. }
  30655. return this._onLoadObservable;
  30656. },
  30657. enumerable: true,
  30658. configurable: true
  30659. });
  30660. Texture.prototype.serialize = function () {
  30661. var serializationObject = _super.prototype.serialize.call(this);
  30662. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30663. serializationObject.base64String = this._buffer;
  30664. serializationObject.name = serializationObject.name.replace("data:", "");
  30665. }
  30666. serializationObject.invertY = this._invertY;
  30667. serializationObject.samplingMode = this.samplingMode;
  30668. return serializationObject;
  30669. };
  30670. Texture.prototype.getClassName = function () {
  30671. return "Texture";
  30672. };
  30673. Texture.prototype.dispose = function () {
  30674. _super.prototype.dispose.call(this);
  30675. if (this.onLoadObservable) {
  30676. this.onLoadObservable.clear();
  30677. this._onLoadObservable = null;
  30678. }
  30679. this._delayedOnLoad = null;
  30680. this._delayedOnError = null;
  30681. };
  30682. // Statics
  30683. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30684. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30685. if (onLoad === void 0) { onLoad = null; }
  30686. if (onError === void 0) { onError = null; }
  30687. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30688. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30689. };
  30690. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30691. if (parsedTexture.customType) {
  30692. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30693. // Update Sampling Mode
  30694. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30695. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30696. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30697. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30698. }
  30699. }
  30700. return parsedCustomTexture;
  30701. }
  30702. if (parsedTexture.isCube) {
  30703. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30704. }
  30705. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30706. return null;
  30707. }
  30708. var texture = BABYLON.SerializationHelper.Parse(function () {
  30709. var generateMipMaps = true;
  30710. if (parsedTexture.noMipmap) {
  30711. generateMipMaps = false;
  30712. }
  30713. if (parsedTexture.mirrorPlane) {
  30714. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30715. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30716. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30717. return mirrorTexture;
  30718. }
  30719. else if (parsedTexture.isRenderTarget) {
  30720. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30721. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30722. return renderTargetTexture;
  30723. }
  30724. else {
  30725. var texture;
  30726. if (parsedTexture.base64String) {
  30727. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30728. }
  30729. else {
  30730. var url = rootUrl + parsedTexture.name;
  30731. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30732. url = parsedTexture.url;
  30733. }
  30734. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30735. }
  30736. return texture;
  30737. }
  30738. }, parsedTexture, scene);
  30739. // Update Sampling Mode
  30740. if (parsedTexture.samplingMode) {
  30741. var sampling = parsedTexture.samplingMode;
  30742. if (texture._samplingMode !== sampling) {
  30743. texture.updateSamplingMode(sampling);
  30744. }
  30745. }
  30746. // Animations
  30747. if (parsedTexture.animations) {
  30748. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30749. var parsedAnimation = parsedTexture.animations[animationIndex];
  30750. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30751. }
  30752. }
  30753. return texture;
  30754. };
  30755. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30756. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30757. if (noMipmap === void 0) { noMipmap = false; }
  30758. if (invertY === void 0) { invertY = true; }
  30759. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30760. if (onLoad === void 0) { onLoad = null; }
  30761. if (onError === void 0) { onError = null; }
  30762. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30763. if (name.substr(0, 5) !== "data:") {
  30764. name = "data:" + name;
  30765. }
  30766. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30767. };
  30768. // Constants
  30769. Texture.NEAREST_SAMPLINGMODE = 1;
  30770. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30771. Texture.BILINEAR_SAMPLINGMODE = 2;
  30772. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30773. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30774. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30775. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30776. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30777. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30778. Texture.NEAREST_LINEAR = 7;
  30779. Texture.NEAREST_NEAREST = 8;
  30780. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30781. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30782. Texture.LINEAR_LINEAR = 11;
  30783. Texture.LINEAR_NEAREST = 12;
  30784. Texture.EXPLICIT_MODE = 0;
  30785. Texture.SPHERICAL_MODE = 1;
  30786. Texture.PLANAR_MODE = 2;
  30787. Texture.CUBIC_MODE = 3;
  30788. Texture.PROJECTION_MODE = 4;
  30789. Texture.SKYBOX_MODE = 5;
  30790. Texture.INVCUBIC_MODE = 6;
  30791. Texture.EQUIRECTANGULAR_MODE = 7;
  30792. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30793. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30794. Texture.CLAMP_ADDRESSMODE = 0;
  30795. Texture.WRAP_ADDRESSMODE = 1;
  30796. Texture.MIRROR_ADDRESSMODE = 2;
  30797. /**
  30798. * 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
  30799. */
  30800. Texture.UseSerializedUrlIfAny = false;
  30801. __decorate([
  30802. BABYLON.serialize()
  30803. ], Texture.prototype, "url", void 0);
  30804. __decorate([
  30805. BABYLON.serialize()
  30806. ], Texture.prototype, "uOffset", void 0);
  30807. __decorate([
  30808. BABYLON.serialize()
  30809. ], Texture.prototype, "vOffset", void 0);
  30810. __decorate([
  30811. BABYLON.serialize()
  30812. ], Texture.prototype, "uScale", void 0);
  30813. __decorate([
  30814. BABYLON.serialize()
  30815. ], Texture.prototype, "vScale", void 0);
  30816. __decorate([
  30817. BABYLON.serialize()
  30818. ], Texture.prototype, "uAng", void 0);
  30819. __decorate([
  30820. BABYLON.serialize()
  30821. ], Texture.prototype, "vAng", void 0);
  30822. __decorate([
  30823. BABYLON.serialize()
  30824. ], Texture.prototype, "wAng", void 0);
  30825. __decorate([
  30826. BABYLON.serialize()
  30827. ], Texture.prototype, "isBlocking", null);
  30828. return Texture;
  30829. }(BABYLON.BaseTexture));
  30830. BABYLON.Texture = Texture;
  30831. })(BABYLON || (BABYLON = {}));
  30832. //# sourceMappingURL=babylon.texture.js.map
  30833. var BABYLON;
  30834. (function (BABYLON) {
  30835. /**
  30836. * @hidden
  30837. **/
  30838. var _InstancesBatch = /** @class */ (function () {
  30839. function _InstancesBatch() {
  30840. this.mustReturn = false;
  30841. this.visibleInstances = new Array();
  30842. this.renderSelf = new Array();
  30843. }
  30844. return _InstancesBatch;
  30845. }());
  30846. BABYLON._InstancesBatch = _InstancesBatch;
  30847. var Mesh = /** @class */ (function (_super) {
  30848. __extends(Mesh, _super);
  30849. /**
  30850. * @constructor
  30851. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30852. * @param {Scene} scene The scene to add this mesh to.
  30853. * @param {Node} parent The parent of this mesh, if it has one
  30854. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30855. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30856. * When false, achieved by calling a clone(), also passing False.
  30857. * This will make creation of children, recursive.
  30858. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30859. */
  30860. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30861. if (scene === void 0) { scene = null; }
  30862. if (parent === void 0) { parent = null; }
  30863. if (source === void 0) { source = null; }
  30864. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30865. var _this = _super.call(this, name, scene) || this;
  30866. // Events
  30867. /**
  30868. * An event triggered before rendering the mesh
  30869. */
  30870. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30871. /**
  30872. * An event triggered after rendering the mesh
  30873. */
  30874. _this.onAfterRenderObservable = new BABYLON.Observable();
  30875. /**
  30876. * An event triggered before drawing the mesh
  30877. */
  30878. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30879. // Members
  30880. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30881. _this.instances = new Array();
  30882. _this._LODLevels = new Array();
  30883. _this._visibleInstances = {};
  30884. _this._renderIdForInstances = new Array();
  30885. _this._batchCache = new _InstancesBatch();
  30886. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30887. // Use by builder only to know what orientation were the mesh build in.
  30888. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30889. _this.overrideMaterialSideOrientation = null;
  30890. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30891. // Will be used to save a source mesh reference, If any
  30892. _this._source = null;
  30893. scene = _this.getScene();
  30894. if (source) {
  30895. // Source mesh
  30896. _this._source = source;
  30897. // Geometry
  30898. if (source._geometry) {
  30899. source._geometry.applyToMesh(_this);
  30900. }
  30901. // Deep copy
  30902. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30903. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30904. // Metadata
  30905. if (source.metadata && source.metadata.clone) {
  30906. _this.metadata = source.metadata.clone();
  30907. }
  30908. else {
  30909. _this.metadata = source.metadata;
  30910. }
  30911. // Tags
  30912. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30913. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30914. }
  30915. // Parent
  30916. _this.parent = source.parent;
  30917. // Pivot
  30918. _this.setPivotMatrix(source.getPivotMatrix());
  30919. _this.id = name + "." + source.id;
  30920. // Material
  30921. _this.material = source.material;
  30922. var index;
  30923. if (!doNotCloneChildren) {
  30924. // Children
  30925. var directDescendants = source.getDescendants(true);
  30926. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30927. var child = directDescendants[index_1];
  30928. if (child.clone) {
  30929. child.clone(name + "." + child.name, _this);
  30930. }
  30931. }
  30932. }
  30933. // Physics clone
  30934. var physicsEngine = _this.getScene().getPhysicsEngine();
  30935. if (clonePhysicsImpostor && physicsEngine) {
  30936. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30937. if (impostor) {
  30938. _this.physicsImpostor = impostor.clone(_this);
  30939. }
  30940. }
  30941. // Particles
  30942. for (index = 0; index < scene.particleSystems.length; index++) {
  30943. var system = scene.particleSystems[index];
  30944. if (system.emitter === source) {
  30945. system.clone(system.name, _this);
  30946. }
  30947. }
  30948. _this.computeWorldMatrix(true);
  30949. }
  30950. // Parent
  30951. if (parent !== null) {
  30952. _this.parent = parent;
  30953. }
  30954. return _this;
  30955. }
  30956. Object.defineProperty(Mesh, "FRONTSIDE", {
  30957. /**
  30958. * Mesh side orientation : usually the external or front surface
  30959. */
  30960. get: function () {
  30961. return Mesh._FRONTSIDE;
  30962. },
  30963. enumerable: true,
  30964. configurable: true
  30965. });
  30966. Object.defineProperty(Mesh, "BACKSIDE", {
  30967. /**
  30968. * Mesh side orientation : usually the internal or back surface
  30969. */
  30970. get: function () {
  30971. return Mesh._BACKSIDE;
  30972. },
  30973. enumerable: true,
  30974. configurable: true
  30975. });
  30976. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30977. /**
  30978. * Mesh side orientation : both internal and external or front and back surfaces
  30979. */
  30980. get: function () {
  30981. return Mesh._DOUBLESIDE;
  30982. },
  30983. enumerable: true,
  30984. configurable: true
  30985. });
  30986. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30987. /**
  30988. * Mesh side orientation : by default, `FRONTSIDE`
  30989. */
  30990. get: function () {
  30991. return Mesh._DEFAULTSIDE;
  30992. },
  30993. enumerable: true,
  30994. configurable: true
  30995. });
  30996. Object.defineProperty(Mesh, "NO_CAP", {
  30997. /**
  30998. * Mesh cap setting : no cap
  30999. */
  31000. get: function () {
  31001. return Mesh._NO_CAP;
  31002. },
  31003. enumerable: true,
  31004. configurable: true
  31005. });
  31006. Object.defineProperty(Mesh, "CAP_START", {
  31007. /**
  31008. * Mesh cap setting : one cap at the beginning of the mesh
  31009. */
  31010. get: function () {
  31011. return Mesh._CAP_START;
  31012. },
  31013. enumerable: true,
  31014. configurable: true
  31015. });
  31016. Object.defineProperty(Mesh, "CAP_END", {
  31017. /**
  31018. * Mesh cap setting : one cap at the end of the mesh
  31019. */
  31020. get: function () {
  31021. return Mesh._CAP_END;
  31022. },
  31023. enumerable: true,
  31024. configurable: true
  31025. });
  31026. Object.defineProperty(Mesh, "CAP_ALL", {
  31027. /**
  31028. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31029. */
  31030. get: function () {
  31031. return Mesh._CAP_ALL;
  31032. },
  31033. enumerable: true,
  31034. configurable: true
  31035. });
  31036. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31037. set: function (callback) {
  31038. if (this._onBeforeDrawObserver) {
  31039. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31040. }
  31041. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31042. },
  31043. enumerable: true,
  31044. configurable: true
  31045. });
  31046. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31047. get: function () {
  31048. return this._morphTargetManager;
  31049. },
  31050. set: function (value) {
  31051. if (this._morphTargetManager === value) {
  31052. return;
  31053. }
  31054. this._morphTargetManager = value;
  31055. this._syncGeometryWithMorphTargetManager();
  31056. },
  31057. enumerable: true,
  31058. configurable: true
  31059. });
  31060. Object.defineProperty(Mesh.prototype, "source", {
  31061. get: function () {
  31062. return this._source;
  31063. },
  31064. enumerable: true,
  31065. configurable: true
  31066. });
  31067. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31068. get: function () {
  31069. return this._unIndexed;
  31070. },
  31071. set: function (value) {
  31072. if (this._unIndexed !== value) {
  31073. this._unIndexed = value;
  31074. this._markSubMeshesAsAttributesDirty();
  31075. }
  31076. },
  31077. enumerable: true,
  31078. configurable: true
  31079. });
  31080. // Methods
  31081. /**
  31082. * Returns the string "Mesh".
  31083. */
  31084. Mesh.prototype.getClassName = function () {
  31085. return "Mesh";
  31086. };
  31087. /**
  31088. * Returns a string.
  31089. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31090. */
  31091. Mesh.prototype.toString = function (fullDetails) {
  31092. var ret = _super.prototype.toString.call(this, fullDetails);
  31093. ret += ", n vertices: " + this.getTotalVertices();
  31094. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31095. if (this.animations) {
  31096. for (var i = 0; i < this.animations.length; i++) {
  31097. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31098. }
  31099. }
  31100. if (fullDetails) {
  31101. if (this._geometry) {
  31102. var ib = this.getIndices();
  31103. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31104. if (vb && ib) {
  31105. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31106. }
  31107. }
  31108. else {
  31109. ret += ", flat shading: UNKNOWN";
  31110. }
  31111. }
  31112. return ret;
  31113. };
  31114. Mesh.prototype._unBindEffect = function () {
  31115. _super.prototype._unBindEffect.call(this);
  31116. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31117. var instance = _a[_i];
  31118. instance._unBindEffect();
  31119. }
  31120. };
  31121. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31122. /**
  31123. * True if the mesh has some Levels Of Details (LOD).
  31124. * Returns a boolean.
  31125. */
  31126. get: function () {
  31127. return this._LODLevels.length > 0;
  31128. },
  31129. enumerable: true,
  31130. configurable: true
  31131. });
  31132. /**
  31133. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31134. * @returns an array of {BABYLON.MeshLODLevel}
  31135. */
  31136. Mesh.prototype.getLODLevels = function () {
  31137. return this._LODLevels;
  31138. };
  31139. Mesh.prototype._sortLODLevels = function () {
  31140. this._LODLevels.sort(function (a, b) {
  31141. if (a.distance < b.distance) {
  31142. return 1;
  31143. }
  31144. if (a.distance > b.distance) {
  31145. return -1;
  31146. }
  31147. return 0;
  31148. });
  31149. };
  31150. /**
  31151. * Add a mesh as LOD level triggered at the given distance.
  31152. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31153. * @param {number} distance The distance from the center of the object to show this level
  31154. * @param {Mesh} mesh The mesh to be added as LOD level
  31155. * @return {Mesh} This mesh (for chaining)
  31156. */
  31157. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31158. if (mesh && mesh._masterMesh) {
  31159. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31160. return this;
  31161. }
  31162. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31163. this._LODLevels.push(level);
  31164. if (mesh) {
  31165. mesh._masterMesh = this;
  31166. }
  31167. this._sortLODLevels();
  31168. return this;
  31169. };
  31170. /**
  31171. * Returns the LOD level mesh at the passed distance or null if not found.
  31172. * It is related to the method `addLODLevel(distance, mesh)`.
  31173. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31174. * Returns an object Mesh or `null`.
  31175. */
  31176. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31177. for (var index = 0; index < this._LODLevels.length; index++) {
  31178. var level = this._LODLevels[index];
  31179. if (level.distance === distance) {
  31180. return level.mesh;
  31181. }
  31182. }
  31183. return null;
  31184. };
  31185. /**
  31186. * Remove a mesh from the LOD array
  31187. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31188. * @param {Mesh} mesh The mesh to be removed.
  31189. * @return {Mesh} This mesh (for chaining)
  31190. */
  31191. Mesh.prototype.removeLODLevel = function (mesh) {
  31192. for (var index = 0; index < this._LODLevels.length; index++) {
  31193. if (this._LODLevels[index].mesh === mesh) {
  31194. this._LODLevels.splice(index, 1);
  31195. if (mesh) {
  31196. mesh._masterMesh = null;
  31197. }
  31198. }
  31199. }
  31200. this._sortLODLevels();
  31201. return this;
  31202. };
  31203. /**
  31204. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31205. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31206. */
  31207. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31208. if (!this._LODLevels || this._LODLevels.length === 0) {
  31209. return this;
  31210. }
  31211. var bSphere;
  31212. if (boundingSphere) {
  31213. bSphere = boundingSphere;
  31214. }
  31215. else {
  31216. var boundingInfo = this.getBoundingInfo();
  31217. bSphere = boundingInfo.boundingSphere;
  31218. }
  31219. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31220. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31221. if (this.onLODLevelSelection) {
  31222. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31223. }
  31224. return this;
  31225. }
  31226. for (var index = 0; index < this._LODLevels.length; index++) {
  31227. var level = this._LODLevels[index];
  31228. if (level.distance < distanceToCamera) {
  31229. if (level.mesh) {
  31230. level.mesh._preActivate();
  31231. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31232. }
  31233. if (this.onLODLevelSelection) {
  31234. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31235. }
  31236. return level.mesh;
  31237. }
  31238. }
  31239. if (this.onLODLevelSelection) {
  31240. this.onLODLevelSelection(distanceToCamera, this, this);
  31241. }
  31242. return this;
  31243. };
  31244. Object.defineProperty(Mesh.prototype, "geometry", {
  31245. /**
  31246. * Returns the mesh internal Geometry object.
  31247. */
  31248. get: function () {
  31249. return this._geometry;
  31250. },
  31251. enumerable: true,
  31252. configurable: true
  31253. });
  31254. /**
  31255. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31256. */
  31257. Mesh.prototype.getTotalVertices = function () {
  31258. if (this._geometry === null || this._geometry === undefined) {
  31259. return 0;
  31260. }
  31261. return this._geometry.getTotalVertices();
  31262. };
  31263. /**
  31264. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31265. * 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.
  31266. * You can force the copy with forceCopy === true
  31267. * Returns null if the mesh has no geometry or no vertex buffer.
  31268. * Possible `kind` values :
  31269. * - BABYLON.VertexBuffer.PositionKind
  31270. * - BABYLON.VertexBuffer.UVKind
  31271. * - BABYLON.VertexBuffer.UV2Kind
  31272. * - BABYLON.VertexBuffer.UV3Kind
  31273. * - BABYLON.VertexBuffer.UV4Kind
  31274. * - BABYLON.VertexBuffer.UV5Kind
  31275. * - BABYLON.VertexBuffer.UV6Kind
  31276. * - BABYLON.VertexBuffer.ColorKind
  31277. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31278. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31279. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31280. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31281. */
  31282. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31283. if (!this._geometry) {
  31284. return null;
  31285. }
  31286. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31287. };
  31288. /**
  31289. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31290. * Returns `null` if the mesh has no geometry.
  31291. * Possible `kind` values :
  31292. * - BABYLON.VertexBuffer.PositionKind
  31293. * - BABYLON.VertexBuffer.UVKind
  31294. * - BABYLON.VertexBuffer.UV2Kind
  31295. * - BABYLON.VertexBuffer.UV3Kind
  31296. * - BABYLON.VertexBuffer.UV4Kind
  31297. * - BABYLON.VertexBuffer.UV5Kind
  31298. * - BABYLON.VertexBuffer.UV6Kind
  31299. * - BABYLON.VertexBuffer.ColorKind
  31300. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31301. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31302. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31303. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31304. */
  31305. Mesh.prototype.getVertexBuffer = function (kind) {
  31306. if (!this._geometry) {
  31307. return null;
  31308. }
  31309. return this._geometry.getVertexBuffer(kind);
  31310. };
  31311. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31312. if (!this._geometry) {
  31313. if (this._delayInfo) {
  31314. return this._delayInfo.indexOf(kind) !== -1;
  31315. }
  31316. return false;
  31317. }
  31318. return this._geometry.isVerticesDataPresent(kind);
  31319. };
  31320. /**
  31321. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31322. * Possible `kind` values :
  31323. * - BABYLON.VertexBuffer.PositionKind
  31324. * - BABYLON.VertexBuffer.UVKind
  31325. * - BABYLON.VertexBuffer.UV2Kind
  31326. * - BABYLON.VertexBuffer.UV3Kind
  31327. * - BABYLON.VertexBuffer.UV4Kind
  31328. * - BABYLON.VertexBuffer.UV5Kind
  31329. * - BABYLON.VertexBuffer.UV6Kind
  31330. * - BABYLON.VertexBuffer.ColorKind
  31331. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31332. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31333. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31334. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31335. */
  31336. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31337. if (!this._geometry) {
  31338. if (this._delayInfo) {
  31339. return this._delayInfo.indexOf(kind) !== -1;
  31340. }
  31341. return false;
  31342. }
  31343. return this._geometry.isVertexBufferUpdatable(kind);
  31344. };
  31345. /**
  31346. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31347. * Possible `kind` values :
  31348. * - BABYLON.VertexBuffer.PositionKind
  31349. * - BABYLON.VertexBuffer.UVKind
  31350. * - BABYLON.VertexBuffer.UV2Kind
  31351. * - BABYLON.VertexBuffer.UV3Kind
  31352. * - BABYLON.VertexBuffer.UV4Kind
  31353. * - BABYLON.VertexBuffer.UV5Kind
  31354. * - BABYLON.VertexBuffer.UV6Kind
  31355. * - BABYLON.VertexBuffer.ColorKind
  31356. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31357. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31358. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31359. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31360. */
  31361. Mesh.prototype.getVerticesDataKinds = function () {
  31362. if (!this._geometry) {
  31363. var result = new Array();
  31364. if (this._delayInfo) {
  31365. this._delayInfo.forEach(function (kind, index, array) {
  31366. result.push(kind);
  31367. });
  31368. }
  31369. return result;
  31370. }
  31371. return this._geometry.getVerticesDataKinds();
  31372. };
  31373. /**
  31374. * Returns a positive integer : the total number of indices in this mesh geometry.
  31375. * Returns zero if the mesh has no geometry.
  31376. */
  31377. Mesh.prototype.getTotalIndices = function () {
  31378. if (!this._geometry) {
  31379. return 0;
  31380. }
  31381. return this._geometry.getTotalIndices();
  31382. };
  31383. /**
  31384. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31385. * 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.
  31386. * Returns an empty array if the mesh has no geometry.
  31387. */
  31388. Mesh.prototype.getIndices = function (copyWhenShared) {
  31389. if (!this._geometry) {
  31390. return [];
  31391. }
  31392. return this._geometry.getIndices(copyWhenShared);
  31393. };
  31394. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31395. get: function () {
  31396. return this._masterMesh !== null && this._masterMesh !== undefined;
  31397. },
  31398. enumerable: true,
  31399. configurable: true
  31400. });
  31401. /**
  31402. * Determine if the current mesh is ready to be rendered
  31403. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31404. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31405. * @returns true if all associated assets are ready (material, textures, shaders)
  31406. */
  31407. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31408. if (completeCheck === void 0) { completeCheck = false; }
  31409. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31410. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31411. return false;
  31412. }
  31413. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31414. return false;
  31415. }
  31416. if (!this.subMeshes || this.subMeshes.length === 0) {
  31417. return true;
  31418. }
  31419. if (!completeCheck) {
  31420. return true;
  31421. }
  31422. var engine = this.getEngine();
  31423. var scene = this.getScene();
  31424. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31425. this.computeWorldMatrix();
  31426. var mat = this.material || scene.defaultMaterial;
  31427. if (mat) {
  31428. if (mat.storeEffectOnSubMeshes) {
  31429. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31430. var subMesh = _a[_i];
  31431. var effectiveMaterial = subMesh.getMaterial();
  31432. if (effectiveMaterial) {
  31433. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31434. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31435. return false;
  31436. }
  31437. }
  31438. else {
  31439. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31440. return false;
  31441. }
  31442. }
  31443. }
  31444. }
  31445. }
  31446. else {
  31447. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31448. return false;
  31449. }
  31450. }
  31451. }
  31452. // Shadows
  31453. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31454. var light = _c[_b];
  31455. var generator = light.getShadowGenerator();
  31456. if (generator) {
  31457. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31458. var subMesh = _e[_d];
  31459. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31460. return false;
  31461. }
  31462. }
  31463. }
  31464. }
  31465. // LOD
  31466. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31467. var lod = _g[_f];
  31468. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31469. return false;
  31470. }
  31471. }
  31472. return true;
  31473. };
  31474. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31475. /**
  31476. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31477. * This property is pertinent only for updatable parametric shapes.
  31478. */
  31479. get: function () {
  31480. return this._areNormalsFrozen;
  31481. },
  31482. enumerable: true,
  31483. configurable: true
  31484. });
  31485. /**
  31486. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31487. * It has no effect at all on other shapes.
  31488. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31489. * Returns the Mesh.
  31490. */
  31491. Mesh.prototype.freezeNormals = function () {
  31492. this._areNormalsFrozen = true;
  31493. return this;
  31494. };
  31495. /**
  31496. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31497. * It has no effect at all on other shapes.
  31498. * It reactivates the mesh normals computation if it was previously frozen.
  31499. * Returns the Mesh.
  31500. */
  31501. Mesh.prototype.unfreezeNormals = function () {
  31502. this._areNormalsFrozen = false;
  31503. return this;
  31504. };
  31505. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31506. /**
  31507. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31508. */
  31509. set: function (count) {
  31510. this._overridenInstanceCount = count;
  31511. },
  31512. enumerable: true,
  31513. configurable: true
  31514. });
  31515. // Methods
  31516. Mesh.prototype._preActivate = function () {
  31517. var sceneRenderId = this.getScene().getRenderId();
  31518. if (this._preActivateId === sceneRenderId) {
  31519. return this;
  31520. }
  31521. this._preActivateId = sceneRenderId;
  31522. this._visibleInstances = null;
  31523. return this;
  31524. };
  31525. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31526. if (this._visibleInstances) {
  31527. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31528. }
  31529. return this;
  31530. };
  31531. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31532. if (!this._visibleInstances) {
  31533. this._visibleInstances = {};
  31534. this._visibleInstances.defaultRenderId = renderId;
  31535. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31536. }
  31537. if (!this._visibleInstances[renderId]) {
  31538. this._visibleInstances[renderId] = new Array();
  31539. }
  31540. this._visibleInstances[renderId].push(instance);
  31541. return this;
  31542. };
  31543. /**
  31544. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31545. * This means the mesh underlying bounding box and sphere are recomputed.
  31546. * Returns the Mesh.
  31547. */
  31548. Mesh.prototype.refreshBoundingInfo = function () {
  31549. return this._refreshBoundingInfo(false);
  31550. };
  31551. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31552. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31553. return this;
  31554. }
  31555. var data = this._getPositionData(applySkeleton);
  31556. if (data) {
  31557. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31558. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31559. }
  31560. if (this.subMeshes) {
  31561. for (var index = 0; index < this.subMeshes.length; index++) {
  31562. this.subMeshes[index].refreshBoundingInfo();
  31563. }
  31564. }
  31565. this._updateBoundingInfo();
  31566. return this;
  31567. };
  31568. Mesh.prototype._getPositionData = function (applySkeleton) {
  31569. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31570. if (data && applySkeleton && this.skeleton) {
  31571. data = BABYLON.Tools.Slice(data);
  31572. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31573. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31574. if (matricesWeightsData && matricesIndicesData) {
  31575. var needExtras = this.numBoneInfluencers > 4;
  31576. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31577. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31578. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31579. var tempVector = BABYLON.Tmp.Vector3[0];
  31580. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31581. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31582. var matWeightIdx = 0;
  31583. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31584. finalMatrix.reset();
  31585. var inf;
  31586. var weight;
  31587. for (inf = 0; inf < 4; inf++) {
  31588. weight = matricesWeightsData[matWeightIdx + inf];
  31589. if (weight <= 0)
  31590. break;
  31591. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31592. finalMatrix.addToSelf(tempMatrix);
  31593. }
  31594. if (needExtras) {
  31595. for (inf = 0; inf < 4; inf++) {
  31596. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31597. if (weight <= 0)
  31598. break;
  31599. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31600. finalMatrix.addToSelf(tempMatrix);
  31601. }
  31602. }
  31603. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31604. tempVector.toArray(data, index);
  31605. }
  31606. }
  31607. }
  31608. return data;
  31609. };
  31610. Mesh.prototype._createGlobalSubMesh = function (force) {
  31611. var totalVertices = this.getTotalVertices();
  31612. if (!totalVertices || !this.getIndices()) {
  31613. return null;
  31614. }
  31615. // Check if we need to recreate the submeshes
  31616. if (this.subMeshes && this.subMeshes.length > 0) {
  31617. var ib = this.getIndices();
  31618. if (!ib) {
  31619. return null;
  31620. }
  31621. var totalIndices = ib.length;
  31622. var needToRecreate = false;
  31623. if (force) {
  31624. needToRecreate = true;
  31625. }
  31626. else {
  31627. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31628. var submesh = _a[_i];
  31629. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31630. needToRecreate = true;
  31631. break;
  31632. }
  31633. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31634. needToRecreate = true;
  31635. break;
  31636. }
  31637. }
  31638. }
  31639. if (!needToRecreate) {
  31640. return this.subMeshes[0];
  31641. }
  31642. }
  31643. this.releaseSubMeshes();
  31644. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31645. };
  31646. Mesh.prototype.subdivide = function (count) {
  31647. if (count < 1) {
  31648. return;
  31649. }
  31650. var totalIndices = this.getTotalIndices();
  31651. var subdivisionSize = (totalIndices / count) | 0;
  31652. var offset = 0;
  31653. // Ensure that subdivisionSize is a multiple of 3
  31654. while (subdivisionSize % 3 !== 0) {
  31655. subdivisionSize++;
  31656. }
  31657. this.releaseSubMeshes();
  31658. for (var index = 0; index < count; index++) {
  31659. if (offset >= totalIndices) {
  31660. break;
  31661. }
  31662. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31663. offset += subdivisionSize;
  31664. }
  31665. this.synchronizeInstances();
  31666. };
  31667. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31668. if (updatable === void 0) { updatable = false; }
  31669. if (!this._geometry) {
  31670. var vertexData = new BABYLON.VertexData();
  31671. vertexData.set(data, kind);
  31672. var scene = this.getScene();
  31673. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31674. }
  31675. else {
  31676. this._geometry.setVerticesData(kind, data, updatable, stride);
  31677. }
  31678. return this;
  31679. };
  31680. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31681. if (updatable === void 0) { updatable = true; }
  31682. var vb = this.getVertexBuffer(kind);
  31683. if (!vb || vb.isUpdatable() === updatable) {
  31684. return;
  31685. }
  31686. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31687. };
  31688. /**
  31689. * Sets the mesh VertexBuffer.
  31690. * Returns the Mesh.
  31691. */
  31692. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31693. if (!this._geometry) {
  31694. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31695. }
  31696. this._geometry.setVerticesBuffer(buffer);
  31697. return this;
  31698. };
  31699. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31700. if (!this._geometry) {
  31701. return this;
  31702. }
  31703. if (!makeItUnique) {
  31704. this._geometry.updateVerticesData(kind, data, updateExtends);
  31705. }
  31706. else {
  31707. this.makeGeometryUnique();
  31708. this.updateVerticesData(kind, data, updateExtends, false);
  31709. }
  31710. return this;
  31711. };
  31712. /**
  31713. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31714. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31715. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31716. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31717. * Returns the Mesh.
  31718. */
  31719. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31720. if (computeNormals === void 0) { computeNormals = true; }
  31721. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31722. if (!positions) {
  31723. return this;
  31724. }
  31725. positionFunction(positions);
  31726. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31727. if (computeNormals) {
  31728. var indices = this.getIndices();
  31729. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31730. if (!normals) {
  31731. return this;
  31732. }
  31733. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31734. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31735. }
  31736. return this;
  31737. };
  31738. /**
  31739. * Creates a un-shared specific occurence of the geometry for the mesh.
  31740. * Returns the Mesh.
  31741. */
  31742. Mesh.prototype.makeGeometryUnique = function () {
  31743. if (!this._geometry) {
  31744. return this;
  31745. }
  31746. var oldGeometry = this._geometry;
  31747. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31748. oldGeometry.releaseForMesh(this, true);
  31749. geometry.applyToMesh(this);
  31750. return this;
  31751. };
  31752. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31753. if (totalVertices === void 0) { totalVertices = null; }
  31754. if (updatable === void 0) { updatable = false; }
  31755. if (!this._geometry) {
  31756. var vertexData = new BABYLON.VertexData();
  31757. vertexData.indices = indices;
  31758. var scene = this.getScene();
  31759. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31760. }
  31761. else {
  31762. this._geometry.setIndices(indices, totalVertices, updatable);
  31763. }
  31764. return this;
  31765. };
  31766. /**
  31767. * Update the current index buffer
  31768. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31769. * Returns the Mesh.
  31770. */
  31771. Mesh.prototype.updateIndices = function (indices, offset) {
  31772. if (!this._geometry) {
  31773. return this;
  31774. }
  31775. this._geometry.updateIndices(indices, offset);
  31776. return this;
  31777. };
  31778. /**
  31779. * Invert the geometry to move from a right handed system to a left handed one.
  31780. * Returns the Mesh.
  31781. */
  31782. Mesh.prototype.toLeftHanded = function () {
  31783. if (!this._geometry) {
  31784. return this;
  31785. }
  31786. this._geometry.toLeftHanded();
  31787. return this;
  31788. };
  31789. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31790. if (!this._geometry) {
  31791. return this;
  31792. }
  31793. var engine = this.getScene().getEngine();
  31794. // Wireframe
  31795. var indexToBind;
  31796. if (this._unIndexed) {
  31797. indexToBind = null;
  31798. }
  31799. else {
  31800. switch (fillMode) {
  31801. case BABYLON.Material.PointFillMode:
  31802. indexToBind = null;
  31803. break;
  31804. case BABYLON.Material.WireFrameFillMode:
  31805. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31806. break;
  31807. default:
  31808. case BABYLON.Material.TriangleFillMode:
  31809. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31810. break;
  31811. }
  31812. }
  31813. // VBOs
  31814. this._geometry._bind(effect, indexToBind);
  31815. return this;
  31816. };
  31817. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31818. if (alternate === void 0) { alternate = false; }
  31819. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31820. return this;
  31821. }
  31822. this.onBeforeDrawObservable.notifyObservers(this);
  31823. var scene = this.getScene();
  31824. var engine = scene.getEngine();
  31825. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31826. // or triangles as points
  31827. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31828. }
  31829. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31830. // Triangles as wireframe
  31831. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31832. }
  31833. else {
  31834. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31835. }
  31836. if (scene._isAlternateRenderingEnabled && !alternate) {
  31837. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31838. if (!effect || !scene.activeCamera) {
  31839. return this;
  31840. }
  31841. scene._switchToAlternateCameraConfiguration(true);
  31842. this._effectiveMaterial.bindView(effect);
  31843. this._effectiveMaterial.bindViewProjection(effect);
  31844. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31845. this._draw(subMesh, fillMode, instancesCount, true);
  31846. engine.setViewport(scene.activeCamera.viewport);
  31847. scene._switchToAlternateCameraConfiguration(false);
  31848. this._effectiveMaterial.bindView(effect);
  31849. this._effectiveMaterial.bindViewProjection(effect);
  31850. }
  31851. return this;
  31852. };
  31853. /**
  31854. * Registers for this mesh a javascript function called just before the rendering process.
  31855. * This function is passed the current mesh.
  31856. * Return the Mesh.
  31857. */
  31858. Mesh.prototype.registerBeforeRender = function (func) {
  31859. this.onBeforeRenderObservable.add(func);
  31860. return this;
  31861. };
  31862. /**
  31863. * Disposes a previously registered javascript function called before the rendering.
  31864. * This function is passed the current mesh.
  31865. * Returns the Mesh.
  31866. */
  31867. Mesh.prototype.unregisterBeforeRender = function (func) {
  31868. this.onBeforeRenderObservable.removeCallback(func);
  31869. return this;
  31870. };
  31871. /**
  31872. * Registers for this mesh a javascript function called just after the rendering is complete.
  31873. * This function is passed the current mesh.
  31874. * Returns the Mesh.
  31875. */
  31876. Mesh.prototype.registerAfterRender = function (func) {
  31877. this.onAfterRenderObservable.add(func);
  31878. return this;
  31879. };
  31880. /**
  31881. * Disposes a previously registered javascript function called after the rendering.
  31882. * This function is passed the current mesh.
  31883. * Return the Mesh.
  31884. */
  31885. Mesh.prototype.unregisterAfterRender = function (func) {
  31886. this.onAfterRenderObservable.removeCallback(func);
  31887. return this;
  31888. };
  31889. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31890. var scene = this.getScene();
  31891. this._batchCache.mustReturn = false;
  31892. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31893. this._batchCache.visibleInstances[subMeshId] = null;
  31894. if (this._visibleInstances) {
  31895. var currentRenderId = scene.getRenderId();
  31896. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31897. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31898. var selfRenderId = this._renderId;
  31899. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31900. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31901. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31902. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31903. }
  31904. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31905. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31906. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31907. this._batchCache.mustReturn = true;
  31908. return this._batchCache;
  31909. }
  31910. if (currentRenderId !== selfRenderId) {
  31911. this._batchCache.renderSelf[subMeshId] = false;
  31912. }
  31913. }
  31914. this._renderIdForInstances[subMeshId] = currentRenderId;
  31915. }
  31916. return this._batchCache;
  31917. };
  31918. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31919. var visibleInstances = batch.visibleInstances[subMesh._id];
  31920. if (!visibleInstances) {
  31921. return this;
  31922. }
  31923. var matricesCount = visibleInstances.length + 1;
  31924. var bufferSize = matricesCount * 16 * 4;
  31925. var currentInstancesBufferSize = this._instancesBufferSize;
  31926. var instancesBuffer = this._instancesBuffer;
  31927. while (this._instancesBufferSize < bufferSize) {
  31928. this._instancesBufferSize *= 2;
  31929. }
  31930. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31931. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31932. }
  31933. var offset = 0;
  31934. var instancesCount = 0;
  31935. var world = this.getWorldMatrix();
  31936. if (batch.renderSelf[subMesh._id]) {
  31937. world.copyToArray(this._instancesData, offset);
  31938. offset += 16;
  31939. instancesCount++;
  31940. }
  31941. if (visibleInstances) {
  31942. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31943. var instance = visibleInstances[instanceIndex];
  31944. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31945. offset += 16;
  31946. instancesCount++;
  31947. }
  31948. }
  31949. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31950. if (instancesBuffer) {
  31951. instancesBuffer.dispose();
  31952. }
  31953. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31954. this._instancesBuffer = instancesBuffer;
  31955. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31956. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31957. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31958. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31959. }
  31960. else {
  31961. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31962. }
  31963. this._bind(subMesh, effect, fillMode);
  31964. this._draw(subMesh, fillMode, instancesCount);
  31965. engine.unbindInstanceAttributes();
  31966. return this;
  31967. };
  31968. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31969. var scene = this.getScene();
  31970. var engine = scene.getEngine();
  31971. if (hardwareInstancedRendering) {
  31972. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31973. }
  31974. else {
  31975. if (batch.renderSelf[subMesh._id]) {
  31976. // Draw
  31977. if (onBeforeDraw) {
  31978. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31979. }
  31980. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31981. }
  31982. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31983. if (visibleInstancesForSubMesh) {
  31984. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31985. var instance = visibleInstancesForSubMesh[instanceIndex];
  31986. // World
  31987. var world = instance.getWorldMatrix();
  31988. if (onBeforeDraw) {
  31989. onBeforeDraw(true, world, effectiveMaterial);
  31990. }
  31991. // Draw
  31992. this._draw(subMesh, fillMode);
  31993. }
  31994. }
  31995. }
  31996. return this;
  31997. };
  31998. /**
  31999. * Triggers the draw call for the mesh.
  32000. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32001. * Returns the Mesh.
  32002. */
  32003. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32004. this._checkOcclusionQuery();
  32005. if (this._isOccluded) {
  32006. return this;
  32007. }
  32008. var scene = this.getScene();
  32009. // Managing instances
  32010. var batch = this._getInstancesRenderList(subMesh._id);
  32011. if (batch.mustReturn) {
  32012. return this;
  32013. }
  32014. // Checking geometry state
  32015. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32016. return this;
  32017. }
  32018. this.onBeforeRenderObservable.notifyObservers(this);
  32019. var engine = scene.getEngine();
  32020. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32021. // Material
  32022. var material = subMesh.getMaterial();
  32023. if (!material) {
  32024. return this;
  32025. }
  32026. this._effectiveMaterial = material;
  32027. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32028. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32029. return this;
  32030. }
  32031. }
  32032. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32033. return this;
  32034. }
  32035. // Alpha mode
  32036. if (enableAlphaMode) {
  32037. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32038. }
  32039. // Outline - step 1
  32040. var savedDepthWrite = engine.getDepthWrite();
  32041. if (this.renderOutline) {
  32042. engine.setDepthWrite(false);
  32043. scene.getOutlineRenderer().render(subMesh, batch);
  32044. engine.setDepthWrite(savedDepthWrite);
  32045. }
  32046. var effect;
  32047. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32048. effect = subMesh.effect;
  32049. }
  32050. else {
  32051. effect = this._effectiveMaterial.getEffect();
  32052. }
  32053. if (!effect) {
  32054. return this;
  32055. }
  32056. var sideOrientation = this.overrideMaterialSideOrientation;
  32057. if (sideOrientation == null) {
  32058. sideOrientation = this._effectiveMaterial.sideOrientation;
  32059. if (this._getWorldMatrixDeterminant() < 0) {
  32060. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32061. }
  32062. }
  32063. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32064. if (this._effectiveMaterial.forceDepthWrite) {
  32065. engine.setDepthWrite(true);
  32066. }
  32067. // Bind
  32068. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32069. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32070. this._bind(subMesh, effect, fillMode);
  32071. }
  32072. var world = this.getWorldMatrix();
  32073. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32074. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32075. }
  32076. else {
  32077. this._effectiveMaterial.bind(world, this);
  32078. }
  32079. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32080. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32081. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32082. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32083. }
  32084. // Draw
  32085. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32086. // Unbind
  32087. this._effectiveMaterial.unbind();
  32088. // Outline - step 2
  32089. if (this.renderOutline && savedDepthWrite) {
  32090. engine.setDepthWrite(true);
  32091. engine.setColorWrite(false);
  32092. scene.getOutlineRenderer().render(subMesh, batch);
  32093. engine.setColorWrite(true);
  32094. }
  32095. // Overlay
  32096. if (this.renderOverlay) {
  32097. var currentMode = engine.getAlphaMode();
  32098. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32099. scene.getOutlineRenderer().render(subMesh, batch, true);
  32100. engine.setAlphaMode(currentMode);
  32101. }
  32102. this.onAfterRenderObservable.notifyObservers(this);
  32103. return this;
  32104. };
  32105. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32106. if (isInstance && effectiveMaterial) {
  32107. effectiveMaterial.bindOnlyWorldMatrix(world);
  32108. }
  32109. };
  32110. /**
  32111. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32112. */
  32113. Mesh.prototype.getEmittedParticleSystems = function () {
  32114. var results = new Array();
  32115. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32116. var particleSystem = this.getScene().particleSystems[index];
  32117. if (particleSystem.emitter === this) {
  32118. results.push(particleSystem);
  32119. }
  32120. }
  32121. return results;
  32122. };
  32123. /**
  32124. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32125. */
  32126. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32127. var results = new Array();
  32128. var descendants = this.getDescendants();
  32129. descendants.push(this);
  32130. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32131. var particleSystem = this.getScene().particleSystems[index];
  32132. var emitter = particleSystem.emitter;
  32133. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32134. results.push(particleSystem);
  32135. }
  32136. }
  32137. return results;
  32138. };
  32139. Mesh.prototype._checkDelayState = function () {
  32140. var scene = this.getScene();
  32141. if (this._geometry) {
  32142. this._geometry.load(scene);
  32143. }
  32144. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32145. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32146. this._queueLoad(scene);
  32147. }
  32148. return this;
  32149. };
  32150. Mesh.prototype._queueLoad = function (scene) {
  32151. var _this = this;
  32152. scene._addPendingData(this);
  32153. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32154. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32155. if (data instanceof ArrayBuffer) {
  32156. _this._delayLoadingFunction(data, _this);
  32157. }
  32158. else {
  32159. _this._delayLoadingFunction(JSON.parse(data), _this);
  32160. }
  32161. _this.instances.forEach(function (instance) {
  32162. instance._syncSubMeshes();
  32163. });
  32164. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32165. scene._removePendingData(_this);
  32166. }, function () { }, scene.database, getBinaryData);
  32167. return this;
  32168. };
  32169. /**
  32170. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32171. */
  32172. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32173. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32174. return false;
  32175. }
  32176. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32177. return false;
  32178. }
  32179. this._checkDelayState();
  32180. return true;
  32181. };
  32182. /**
  32183. * Sets the mesh material by the material or multiMaterial `id` property.
  32184. * The material `id` is a string identifying the material or the multiMaterial.
  32185. * This method returns the Mesh.
  32186. */
  32187. Mesh.prototype.setMaterialByID = function (id) {
  32188. var materials = this.getScene().materials;
  32189. var index;
  32190. for (index = materials.length - 1; index > -1; index--) {
  32191. if (materials[index].id === id) {
  32192. this.material = materials[index];
  32193. return this;
  32194. }
  32195. }
  32196. // Multi
  32197. var multiMaterials = this.getScene().multiMaterials;
  32198. for (index = multiMaterials.length - 1; index > -1; index--) {
  32199. if (multiMaterials[index].id === id) {
  32200. this.material = multiMaterials[index];
  32201. return this;
  32202. }
  32203. }
  32204. return this;
  32205. };
  32206. /**
  32207. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32208. */
  32209. Mesh.prototype.getAnimatables = function () {
  32210. var results = new Array();
  32211. if (this.material) {
  32212. results.push(this.material);
  32213. }
  32214. if (this.skeleton) {
  32215. results.push(this.skeleton);
  32216. }
  32217. return results;
  32218. };
  32219. /**
  32220. * Modifies the mesh geometry according to the passed transformation matrix.
  32221. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32222. * The mesh normals are modified accordingly the same transformation.
  32223. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32224. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32225. * Returns the Mesh.
  32226. */
  32227. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32228. // Position
  32229. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32230. return this;
  32231. }
  32232. var submeshes = this.subMeshes.splice(0);
  32233. this._resetPointsArrayCache();
  32234. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32235. var temp = new Array();
  32236. var index;
  32237. for (index = 0; index < data.length; index += 3) {
  32238. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32239. }
  32240. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32241. // Normals
  32242. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32243. return this;
  32244. }
  32245. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32246. temp = [];
  32247. for (index = 0; index < data.length; index += 3) {
  32248. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32249. }
  32250. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32251. // flip faces?
  32252. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32253. this.flipFaces();
  32254. }
  32255. // Restore submeshes
  32256. this.releaseSubMeshes();
  32257. this.subMeshes = submeshes;
  32258. return this;
  32259. };
  32260. /**
  32261. * Modifies the mesh geometry according to its own current World Matrix.
  32262. * The mesh World Matrix is then reset.
  32263. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32264. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32265. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32266. * Returns the Mesh.
  32267. */
  32268. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32269. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32270. this.scaling.copyFromFloats(1, 1, 1);
  32271. this.position.copyFromFloats(0, 0, 0);
  32272. this.rotation.copyFromFloats(0, 0, 0);
  32273. //only if quaternion is already set
  32274. if (this.rotationQuaternion) {
  32275. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32276. }
  32277. this._worldMatrix = BABYLON.Matrix.Identity();
  32278. return this;
  32279. };
  32280. Object.defineProperty(Mesh.prototype, "_positions", {
  32281. // Cache
  32282. get: function () {
  32283. if (this._geometry) {
  32284. return this._geometry._positions;
  32285. }
  32286. return null;
  32287. },
  32288. enumerable: true,
  32289. configurable: true
  32290. });
  32291. Mesh.prototype._resetPointsArrayCache = function () {
  32292. if (this._geometry) {
  32293. this._geometry._resetPointsArrayCache();
  32294. }
  32295. return this;
  32296. };
  32297. Mesh.prototype._generatePointsArray = function () {
  32298. if (this._geometry) {
  32299. return this._geometry._generatePointsArray();
  32300. }
  32301. return false;
  32302. };
  32303. /**
  32304. * Returns a new Mesh object generated from the current mesh properties.
  32305. * This method must not get confused with createInstance().
  32306. * The parameter `name` is a string, the name given to the new mesh.
  32307. * The optional parameter `newParent` can be any Node object (default `null`).
  32308. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32309. * 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.
  32310. */
  32311. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32312. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32313. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32314. };
  32315. /**
  32316. * Releases resources associated with this mesh.
  32317. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32318. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32319. */
  32320. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32321. var _this = this;
  32322. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32323. this.morphTargetManager = null;
  32324. if (this._geometry) {
  32325. this._geometry.releaseForMesh(this, true);
  32326. }
  32327. // Sources
  32328. var meshes = this.getScene().meshes;
  32329. meshes.forEach(function (abstractMesh) {
  32330. var mesh = abstractMesh;
  32331. if (mesh._source && mesh._source === _this) {
  32332. mesh._source = null;
  32333. }
  32334. });
  32335. this._source = null;
  32336. // Instances
  32337. if (this._instancesBuffer) {
  32338. this._instancesBuffer.dispose();
  32339. this._instancesBuffer = null;
  32340. }
  32341. while (this.instances.length) {
  32342. this.instances[0].dispose();
  32343. }
  32344. // Effect layers.
  32345. var effectLayers = this.getScene().effectLayers;
  32346. for (var i = 0; i < effectLayers.length; i++) {
  32347. var effectLayer = effectLayers[i];
  32348. if (effectLayer) {
  32349. effectLayer._disposeMesh(this);
  32350. }
  32351. }
  32352. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32353. };
  32354. /**
  32355. * Modifies the mesh geometry according to a displacement map.
  32356. * 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.
  32357. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32358. * This method returns nothing.
  32359. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32360. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32361. * 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.
  32362. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32363. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32364. *
  32365. * Returns the Mesh.
  32366. */
  32367. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32368. var _this = this;
  32369. var scene = this.getScene();
  32370. var onload = function (img) {
  32371. // Getting height map data
  32372. var canvas = document.createElement("canvas");
  32373. var context = canvas.getContext("2d");
  32374. var heightMapWidth = img.width;
  32375. var heightMapHeight = img.height;
  32376. canvas.width = heightMapWidth;
  32377. canvas.height = heightMapHeight;
  32378. context.drawImage(img, 0, 0);
  32379. // Create VertexData from map data
  32380. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32381. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32382. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32383. //execute success callback, if set
  32384. if (onSuccess) {
  32385. onSuccess(_this);
  32386. }
  32387. };
  32388. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32389. return this;
  32390. };
  32391. /**
  32392. * Modifies the mesh geometry according to a displacementMap buffer.
  32393. * 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.
  32394. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32395. * This method returns nothing.
  32396. * 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.
  32397. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32398. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32399. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32400. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32401. *
  32402. * Returns the Mesh.
  32403. */
  32404. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32405. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32406. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32407. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32408. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32409. return this;
  32410. }
  32411. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32412. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32413. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32414. var position = BABYLON.Vector3.Zero();
  32415. var normal = BABYLON.Vector3.Zero();
  32416. var uv = BABYLON.Vector2.Zero();
  32417. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32418. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32419. for (var index = 0; index < positions.length; index += 3) {
  32420. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32421. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32422. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32423. // Compute height
  32424. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32425. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32426. var pos = (u + v * heightMapWidth) * 4;
  32427. var r = buffer[pos] / 255.0;
  32428. var g = buffer[pos + 1] / 255.0;
  32429. var b = buffer[pos + 2] / 255.0;
  32430. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32431. normal.normalize();
  32432. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32433. position = position.add(normal);
  32434. position.toArray(positions, index);
  32435. }
  32436. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32437. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32438. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32439. return this;
  32440. };
  32441. /**
  32442. * Modify the mesh to get a flat shading rendering.
  32443. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32444. * This method returns the Mesh.
  32445. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32446. */
  32447. Mesh.prototype.convertToFlatShadedMesh = function () {
  32448. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32449. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32450. var kinds = this.getVerticesDataKinds();
  32451. var vbs = {};
  32452. var data = {};
  32453. var newdata = {};
  32454. var updatableNormals = false;
  32455. var kindIndex;
  32456. var kind;
  32457. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32458. kind = kinds[kindIndex];
  32459. var vertexBuffer = this.getVertexBuffer(kind);
  32460. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32461. updatableNormals = vertexBuffer.isUpdatable();
  32462. kinds.splice(kindIndex, 1);
  32463. kindIndex--;
  32464. continue;
  32465. }
  32466. vbs[kind] = vertexBuffer;
  32467. data[kind] = vbs[kind].getData();
  32468. newdata[kind] = [];
  32469. }
  32470. // Save previous submeshes
  32471. var previousSubmeshes = this.subMeshes.slice(0);
  32472. var indices = this.getIndices();
  32473. var totalIndices = this.getTotalIndices();
  32474. // Generating unique vertices per face
  32475. var index;
  32476. for (index = 0; index < totalIndices; index++) {
  32477. var vertexIndex = indices[index];
  32478. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32479. kind = kinds[kindIndex];
  32480. var stride = vbs[kind].getStrideSize();
  32481. for (var offset = 0; offset < stride; offset++) {
  32482. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32483. }
  32484. }
  32485. }
  32486. // Updating faces & normal
  32487. var normals = [];
  32488. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32489. for (index = 0; index < totalIndices; index += 3) {
  32490. indices[index] = index;
  32491. indices[index + 1] = index + 1;
  32492. indices[index + 2] = index + 2;
  32493. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32494. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32495. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32496. var p1p2 = p1.subtract(p2);
  32497. var p3p2 = p3.subtract(p2);
  32498. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32499. // Store same normals for every vertex
  32500. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32501. normals.push(normal.x);
  32502. normals.push(normal.y);
  32503. normals.push(normal.z);
  32504. }
  32505. }
  32506. this.setIndices(indices);
  32507. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32508. // Updating vertex buffers
  32509. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32510. kind = kinds[kindIndex];
  32511. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32512. }
  32513. // Updating submeshes
  32514. this.releaseSubMeshes();
  32515. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32516. var previousOne = previousSubmeshes[submeshIndex];
  32517. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32518. }
  32519. this.synchronizeInstances();
  32520. return this;
  32521. };
  32522. /**
  32523. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32524. * In other words, more vertices, no more indices and a single bigger VBO.
  32525. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32526. * Returns the Mesh.
  32527. */
  32528. Mesh.prototype.convertToUnIndexedMesh = function () {
  32529. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32530. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32531. var kinds = this.getVerticesDataKinds();
  32532. var vbs = {};
  32533. var data = {};
  32534. var newdata = {};
  32535. var kindIndex;
  32536. var kind;
  32537. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32538. kind = kinds[kindIndex];
  32539. var vertexBuffer = this.getVertexBuffer(kind);
  32540. vbs[kind] = vertexBuffer;
  32541. data[kind] = vbs[kind].getData();
  32542. newdata[kind] = [];
  32543. }
  32544. // Save previous submeshes
  32545. var previousSubmeshes = this.subMeshes.slice(0);
  32546. var indices = this.getIndices();
  32547. var totalIndices = this.getTotalIndices();
  32548. // Generating unique vertices per face
  32549. var index;
  32550. for (index = 0; index < totalIndices; index++) {
  32551. var vertexIndex = indices[index];
  32552. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32553. kind = kinds[kindIndex];
  32554. var stride = vbs[kind].getStrideSize();
  32555. for (var offset = 0; offset < stride; offset++) {
  32556. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32557. }
  32558. }
  32559. }
  32560. // Updating indices
  32561. for (index = 0; index < totalIndices; index += 3) {
  32562. indices[index] = index;
  32563. indices[index + 1] = index + 1;
  32564. indices[index + 2] = index + 2;
  32565. }
  32566. this.setIndices(indices);
  32567. // Updating vertex buffers
  32568. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32569. kind = kinds[kindIndex];
  32570. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32571. }
  32572. // Updating submeshes
  32573. this.releaseSubMeshes();
  32574. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32575. var previousOne = previousSubmeshes[submeshIndex];
  32576. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32577. }
  32578. this._unIndexed = true;
  32579. this.synchronizeInstances();
  32580. return this;
  32581. };
  32582. /**
  32583. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32584. * This method returns the Mesh.
  32585. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32586. */
  32587. Mesh.prototype.flipFaces = function (flipNormals) {
  32588. if (flipNormals === void 0) { flipNormals = false; }
  32589. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32590. var i;
  32591. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32592. for (i = 0; i < vertex_data.normals.length; i++) {
  32593. vertex_data.normals[i] *= -1;
  32594. }
  32595. }
  32596. if (vertex_data.indices) {
  32597. var temp;
  32598. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32599. // reassign indices
  32600. temp = vertex_data.indices[i + 1];
  32601. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32602. vertex_data.indices[i + 2] = temp;
  32603. }
  32604. }
  32605. vertex_data.applyToMesh(this);
  32606. return this;
  32607. };
  32608. // Instances
  32609. /**
  32610. * Creates a new InstancedMesh object from the mesh model.
  32611. * An instance shares the same properties and the same material than its model.
  32612. * Only these properties of each instance can then be set individually :
  32613. * - position
  32614. * - rotation
  32615. * - rotationQuaternion
  32616. * - setPivotMatrix
  32617. * - scaling
  32618. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32619. * Warning : this method is not supported for Line mesh and LineSystem
  32620. */
  32621. Mesh.prototype.createInstance = function (name) {
  32622. return new BABYLON.InstancedMesh(name, this);
  32623. };
  32624. /**
  32625. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32626. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32627. * This method returns the Mesh.
  32628. */
  32629. Mesh.prototype.synchronizeInstances = function () {
  32630. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32631. var instance = this.instances[instanceIndex];
  32632. instance._syncSubMeshes();
  32633. }
  32634. return this;
  32635. };
  32636. /**
  32637. * Simplify the mesh according to the given array of settings.
  32638. * Function will return immediately and will simplify async. It returns the Mesh.
  32639. * @param settings a collection of simplification settings.
  32640. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32641. * @param type the type of simplification to run.
  32642. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32643. */
  32644. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32645. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32646. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32647. this.getScene().simplificationQueue.addTask({
  32648. settings: settings,
  32649. parallelProcessing: parallelProcessing,
  32650. mesh: this,
  32651. simplificationType: simplificationType,
  32652. successCallback: successCallback
  32653. });
  32654. return this;
  32655. };
  32656. /**
  32657. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32658. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32659. * This should be used together with the simplification to avoid disappearing triangles.
  32660. * Returns the Mesh.
  32661. * @param successCallback an optional success callback to be called after the optimization finished.
  32662. */
  32663. Mesh.prototype.optimizeIndices = function (successCallback) {
  32664. var _this = this;
  32665. var indices = this.getIndices();
  32666. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32667. if (!positions || !indices) {
  32668. return this;
  32669. }
  32670. var vectorPositions = new Array();
  32671. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32672. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32673. }
  32674. var dupes = new Array();
  32675. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32676. var realPos = vectorPositions.length - 1 - iteration;
  32677. var testedPosition = vectorPositions[realPos];
  32678. for (var j = 0; j < realPos; ++j) {
  32679. var againstPosition = vectorPositions[j];
  32680. if (testedPosition.equals(againstPosition)) {
  32681. dupes[realPos] = j;
  32682. break;
  32683. }
  32684. }
  32685. }, function () {
  32686. for (var i = 0; i < indices.length; ++i) {
  32687. indices[i] = dupes[indices[i]] || indices[i];
  32688. }
  32689. //indices are now reordered
  32690. var originalSubMeshes = _this.subMeshes.slice(0);
  32691. _this.setIndices(indices);
  32692. _this.subMeshes = originalSubMeshes;
  32693. if (successCallback) {
  32694. successCallback(_this);
  32695. }
  32696. });
  32697. return this;
  32698. };
  32699. Mesh.prototype.serialize = function (serializationObject) {
  32700. serializationObject.name = this.name;
  32701. serializationObject.id = this.id;
  32702. serializationObject.type = this.getClassName();
  32703. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32704. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32705. }
  32706. serializationObject.position = this.position.asArray();
  32707. if (this.rotationQuaternion) {
  32708. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32709. }
  32710. else if (this.rotation) {
  32711. serializationObject.rotation = this.rotation.asArray();
  32712. }
  32713. serializationObject.scaling = this.scaling.asArray();
  32714. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32715. serializationObject.isEnabled = this.isEnabled(false);
  32716. serializationObject.isVisible = this.isVisible;
  32717. serializationObject.infiniteDistance = this.infiniteDistance;
  32718. serializationObject.pickable = this.isPickable;
  32719. serializationObject.receiveShadows = this.receiveShadows;
  32720. serializationObject.billboardMode = this.billboardMode;
  32721. serializationObject.visibility = this.visibility;
  32722. serializationObject.checkCollisions = this.checkCollisions;
  32723. serializationObject.isBlocker = this.isBlocker;
  32724. // Parent
  32725. if (this.parent) {
  32726. serializationObject.parentId = this.parent.id;
  32727. }
  32728. // Geometry
  32729. serializationObject.isUnIndexed = this.isUnIndexed;
  32730. var geometry = this._geometry;
  32731. if (geometry) {
  32732. var geometryId = geometry.id;
  32733. serializationObject.geometryId = geometryId;
  32734. // SubMeshes
  32735. serializationObject.subMeshes = [];
  32736. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32737. var subMesh = this.subMeshes[subIndex];
  32738. serializationObject.subMeshes.push({
  32739. materialIndex: subMesh.materialIndex,
  32740. verticesStart: subMesh.verticesStart,
  32741. verticesCount: subMesh.verticesCount,
  32742. indexStart: subMesh.indexStart,
  32743. indexCount: subMesh.indexCount
  32744. });
  32745. }
  32746. }
  32747. // Material
  32748. if (this.material) {
  32749. serializationObject.materialId = this.material.id;
  32750. }
  32751. else {
  32752. this.material = null;
  32753. }
  32754. // Morph targets
  32755. if (this.morphTargetManager) {
  32756. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32757. }
  32758. // Skeleton
  32759. if (this.skeleton) {
  32760. serializationObject.skeletonId = this.skeleton.id;
  32761. }
  32762. // Physics
  32763. //TODO implement correct serialization for physics impostors.
  32764. var impostor = this.getPhysicsImpostor();
  32765. if (impostor) {
  32766. serializationObject.physicsMass = impostor.getParam("mass");
  32767. serializationObject.physicsFriction = impostor.getParam("friction");
  32768. serializationObject.physicsRestitution = impostor.getParam("mass");
  32769. serializationObject.physicsImpostor = impostor.type;
  32770. }
  32771. // Metadata
  32772. if (this.metadata) {
  32773. serializationObject.metadata = this.metadata;
  32774. }
  32775. // Instances
  32776. serializationObject.instances = [];
  32777. for (var index = 0; index < this.instances.length; index++) {
  32778. var instance = this.instances[index];
  32779. var serializationInstance = {
  32780. name: instance.name,
  32781. id: instance.id,
  32782. position: instance.position.asArray(),
  32783. scaling: instance.scaling.asArray()
  32784. };
  32785. if (instance.rotationQuaternion) {
  32786. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32787. }
  32788. else if (instance.rotation) {
  32789. serializationInstance.rotation = instance.rotation.asArray();
  32790. }
  32791. serializationObject.instances.push(serializationInstance);
  32792. // Animations
  32793. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32794. serializationInstance.ranges = instance.serializeAnimationRanges();
  32795. }
  32796. //
  32797. // Animations
  32798. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32799. serializationObject.ranges = this.serializeAnimationRanges();
  32800. // Layer mask
  32801. serializationObject.layerMask = this.layerMask;
  32802. // Alpha
  32803. serializationObject.alphaIndex = this.alphaIndex;
  32804. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32805. // Overlay
  32806. serializationObject.overlayAlpha = this.overlayAlpha;
  32807. serializationObject.overlayColor = this.overlayColor.asArray();
  32808. serializationObject.renderOverlay = this.renderOverlay;
  32809. // Fog
  32810. serializationObject.applyFog = this.applyFog;
  32811. // Action Manager
  32812. if (this.actionManager) {
  32813. serializationObject.actions = this.actionManager.serialize(this.name);
  32814. }
  32815. };
  32816. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32817. if (!this.geometry) {
  32818. return;
  32819. }
  32820. this._markSubMeshesAsAttributesDirty();
  32821. var morphTargetManager = this._morphTargetManager;
  32822. if (morphTargetManager && morphTargetManager.vertexCount) {
  32823. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32824. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32825. this.morphTargetManager = null;
  32826. return;
  32827. }
  32828. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32829. var morphTarget = morphTargetManager.getActiveTarget(index);
  32830. var positions = morphTarget.getPositions();
  32831. if (!positions) {
  32832. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32833. return;
  32834. }
  32835. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32836. var normals = morphTarget.getNormals();
  32837. if (normals) {
  32838. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32839. }
  32840. var tangents = morphTarget.getTangents();
  32841. if (tangents) {
  32842. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32843. }
  32844. }
  32845. }
  32846. else {
  32847. var index = 0;
  32848. // Positions
  32849. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32850. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32851. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32852. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32853. }
  32854. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32855. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32856. }
  32857. index++;
  32858. }
  32859. }
  32860. };
  32861. // Statics
  32862. /**
  32863. * Returns a new Mesh object parsed from the source provided.
  32864. * The parameter `parsedMesh` is the source.
  32865. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32866. */
  32867. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32868. var mesh;
  32869. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32870. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32871. }
  32872. else {
  32873. mesh = new Mesh(parsedMesh.name, scene);
  32874. }
  32875. mesh.id = parsedMesh.id;
  32876. if (BABYLON.Tags) {
  32877. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32878. }
  32879. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32880. if (parsedMesh.metadata !== undefined) {
  32881. mesh.metadata = parsedMesh.metadata;
  32882. }
  32883. if (parsedMesh.rotationQuaternion) {
  32884. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32885. }
  32886. else if (parsedMesh.rotation) {
  32887. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32888. }
  32889. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32890. if (parsedMesh.localMatrix) {
  32891. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32892. }
  32893. else if (parsedMesh.pivotMatrix) {
  32894. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32895. }
  32896. mesh.setEnabled(parsedMesh.isEnabled);
  32897. mesh.isVisible = parsedMesh.isVisible;
  32898. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32899. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32900. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32901. if (parsedMesh.applyFog !== undefined) {
  32902. mesh.applyFog = parsedMesh.applyFog;
  32903. }
  32904. if (parsedMesh.pickable !== undefined) {
  32905. mesh.isPickable = parsedMesh.pickable;
  32906. }
  32907. if (parsedMesh.alphaIndex !== undefined) {
  32908. mesh.alphaIndex = parsedMesh.alphaIndex;
  32909. }
  32910. mesh.receiveShadows = parsedMesh.receiveShadows;
  32911. mesh.billboardMode = parsedMesh.billboardMode;
  32912. if (parsedMesh.visibility !== undefined) {
  32913. mesh.visibility = parsedMesh.visibility;
  32914. }
  32915. mesh.checkCollisions = parsedMesh.checkCollisions;
  32916. if (parsedMesh.isBlocker !== undefined) {
  32917. mesh.isBlocker = parsedMesh.isBlocker;
  32918. }
  32919. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32920. // freezeWorldMatrix
  32921. if (parsedMesh.freezeWorldMatrix) {
  32922. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32923. }
  32924. // Parent
  32925. if (parsedMesh.parentId) {
  32926. mesh._waitingParentId = parsedMesh.parentId;
  32927. }
  32928. // Actions
  32929. if (parsedMesh.actions !== undefined) {
  32930. mesh._waitingActions = parsedMesh.actions;
  32931. }
  32932. // Overlay
  32933. if (parsedMesh.overlayAlpha !== undefined) {
  32934. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32935. }
  32936. if (parsedMesh.overlayColor !== undefined) {
  32937. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32938. }
  32939. if (parsedMesh.renderOverlay !== undefined) {
  32940. mesh.renderOverlay = parsedMesh.renderOverlay;
  32941. }
  32942. // Geometry
  32943. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32944. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32945. if (parsedMesh.delayLoadingFile) {
  32946. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32947. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32948. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32949. if (parsedMesh._binaryInfo) {
  32950. mesh._binaryInfo = parsedMesh._binaryInfo;
  32951. }
  32952. mesh._delayInfo = [];
  32953. if (parsedMesh.hasUVs) {
  32954. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32955. }
  32956. if (parsedMesh.hasUVs2) {
  32957. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32958. }
  32959. if (parsedMesh.hasUVs3) {
  32960. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32961. }
  32962. if (parsedMesh.hasUVs4) {
  32963. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32964. }
  32965. if (parsedMesh.hasUVs5) {
  32966. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32967. }
  32968. if (parsedMesh.hasUVs6) {
  32969. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32970. }
  32971. if (parsedMesh.hasColors) {
  32972. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32973. }
  32974. if (parsedMesh.hasMatricesIndices) {
  32975. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32976. }
  32977. if (parsedMesh.hasMatricesWeights) {
  32978. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32979. }
  32980. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32981. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32982. mesh._checkDelayState();
  32983. }
  32984. }
  32985. else {
  32986. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32987. }
  32988. // Material
  32989. if (parsedMesh.materialId) {
  32990. mesh.setMaterialByID(parsedMesh.materialId);
  32991. }
  32992. else {
  32993. mesh.material = null;
  32994. }
  32995. // Morph targets
  32996. if (parsedMesh.morphTargetManagerId > -1) {
  32997. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32998. }
  32999. // Skeleton
  33000. if (parsedMesh.skeletonId > -1) {
  33001. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33002. if (parsedMesh.numBoneInfluencers) {
  33003. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33004. }
  33005. }
  33006. // Animations
  33007. if (parsedMesh.animations) {
  33008. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33009. var parsedAnimation = parsedMesh.animations[animationIndex];
  33010. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33011. }
  33012. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33013. }
  33014. if (parsedMesh.autoAnimate) {
  33015. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33016. }
  33017. // Layer Mask
  33018. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33019. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33020. }
  33021. else {
  33022. mesh.layerMask = 0x0FFFFFFF;
  33023. }
  33024. // Physics
  33025. if (parsedMesh.physicsImpostor) {
  33026. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33027. mass: parsedMesh.physicsMass,
  33028. friction: parsedMesh.physicsFriction,
  33029. restitution: parsedMesh.physicsRestitution
  33030. }, scene);
  33031. }
  33032. // Instances
  33033. if (parsedMesh.instances) {
  33034. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33035. var parsedInstance = parsedMesh.instances[index];
  33036. var instance = mesh.createInstance(parsedInstance.name);
  33037. if (parsedInstance.id) {
  33038. instance.id = parsedInstance.id;
  33039. }
  33040. if (BABYLON.Tags) {
  33041. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33042. }
  33043. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33044. if (parsedInstance.parentId) {
  33045. instance._waitingParentId = parsedInstance.parentId;
  33046. }
  33047. if (parsedInstance.rotationQuaternion) {
  33048. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33049. }
  33050. else if (parsedInstance.rotation) {
  33051. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33052. }
  33053. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33054. instance.checkCollisions = mesh.checkCollisions;
  33055. if (parsedMesh.animations) {
  33056. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33057. parsedAnimation = parsedMesh.animations[animationIndex];
  33058. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33059. }
  33060. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33061. }
  33062. }
  33063. }
  33064. return mesh;
  33065. };
  33066. /**
  33067. * Creates a ribbon mesh.
  33068. * Please consider using the same method from the MeshBuilder class instead.
  33069. * 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.
  33070. *
  33071. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33072. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33073. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33074. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33075. * 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.
  33076. * 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.
  33077. * 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
  33078. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33079. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33081. */
  33082. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33083. if (closeArray === void 0) { closeArray = false; }
  33084. if (updatable === void 0) { updatable = false; }
  33085. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33086. pathArray: pathArray,
  33087. closeArray: closeArray,
  33088. closePath: closePath,
  33089. offset: offset,
  33090. updatable: updatable,
  33091. sideOrientation: sideOrientation,
  33092. instance: instance
  33093. }, scene);
  33094. };
  33095. /**
  33096. * Creates a plane polygonal mesh. By default, this is a disc.
  33097. * Please consider using the same method from the MeshBuilder class instead.
  33098. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33099. * 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.
  33100. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33101. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33103. */
  33104. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33105. if (scene === void 0) { scene = null; }
  33106. var options = {
  33107. radius: radius,
  33108. tessellation: tessellation,
  33109. sideOrientation: sideOrientation,
  33110. updatable: updatable
  33111. };
  33112. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33113. };
  33114. /**
  33115. * Creates a box mesh.
  33116. * Please consider using the same method from the MeshBuilder class instead.
  33117. * The parameter `size` sets the size (float) of each box side (default 1).
  33118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33119. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33121. */
  33122. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33123. if (scene === void 0) { scene = null; }
  33124. var options = {
  33125. size: size,
  33126. sideOrientation: sideOrientation,
  33127. updatable: updatable
  33128. };
  33129. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33130. };
  33131. /**
  33132. * Creates a sphere mesh.
  33133. * Please consider using the same method from the MeshBuilder class instead.
  33134. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33135. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33136. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33137. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33138. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33139. */
  33140. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33141. var options = {
  33142. segments: segments,
  33143. diameterX: diameter,
  33144. diameterY: diameter,
  33145. diameterZ: diameter,
  33146. sideOrientation: sideOrientation,
  33147. updatable: updatable
  33148. };
  33149. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33150. };
  33151. /**
  33152. * Creates a cylinder or a cone mesh.
  33153. * Please consider using the same method from the MeshBuilder class instead.
  33154. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33155. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33156. * 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.
  33157. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33158. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33160. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33162. */
  33163. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33164. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33165. if (scene !== undefined) {
  33166. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33167. updatable = scene;
  33168. }
  33169. scene = subdivisions;
  33170. subdivisions = 1;
  33171. }
  33172. var options = {
  33173. height: height,
  33174. diameterTop: diameterTop,
  33175. diameterBottom: diameterBottom,
  33176. tessellation: tessellation,
  33177. subdivisions: subdivisions,
  33178. sideOrientation: sideOrientation,
  33179. updatable: updatable
  33180. };
  33181. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33182. };
  33183. // Torus (Code from SharpDX.org)
  33184. /**
  33185. * Creates a torus mesh.
  33186. * Please consider using the same method from the MeshBuilder class instead.
  33187. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33188. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33189. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33190. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33191. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33193. */
  33194. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33195. var options = {
  33196. diameter: diameter,
  33197. thickness: thickness,
  33198. tessellation: tessellation,
  33199. sideOrientation: sideOrientation,
  33200. updatable: updatable
  33201. };
  33202. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33203. };
  33204. /**
  33205. * Creates a torus knot mesh.
  33206. * Please consider using the same method from the MeshBuilder class instead.
  33207. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33208. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33209. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33210. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33211. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33212. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33214. */
  33215. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33216. var options = {
  33217. radius: radius,
  33218. tube: tube,
  33219. radialSegments: radialSegments,
  33220. tubularSegments: tubularSegments,
  33221. p: p,
  33222. q: q,
  33223. sideOrientation: sideOrientation,
  33224. updatable: updatable
  33225. };
  33226. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33227. };
  33228. /**
  33229. * Creates a line mesh.
  33230. * Please consider using the same method from the MeshBuilder class instead.
  33231. * 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.
  33232. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33233. * The parameter `points` is an array successive Vector3.
  33234. * 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
  33235. * When updating an instance, remember that only point positions can change, not the number of points.
  33236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33237. */
  33238. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33239. if (scene === void 0) { scene = null; }
  33240. if (updatable === void 0) { updatable = false; }
  33241. if (instance === void 0) { instance = null; }
  33242. var options = {
  33243. points: points,
  33244. updatable: updatable,
  33245. instance: instance
  33246. };
  33247. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33248. };
  33249. /**
  33250. * Creates a dashed line mesh.
  33251. * Please consider using the same method from the MeshBuilder class instead.
  33252. * 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.
  33253. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33254. * The parameter `points` is an array successive Vector3.
  33255. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33256. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33257. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33258. * 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
  33259. * When updating an instance, remember that only point positions can change, not the number of points.
  33260. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33261. */
  33262. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33263. if (scene === void 0) { scene = null; }
  33264. var options = {
  33265. points: points,
  33266. dashSize: dashSize,
  33267. gapSize: gapSize,
  33268. dashNb: dashNb,
  33269. updatable: updatable,
  33270. instance: instance
  33271. };
  33272. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33273. };
  33274. /**
  33275. * Creates a polygon mesh.
  33276. * Please consider using the same method from the MeshBuilder class instead.
  33277. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33278. * 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.
  33279. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33281. * Remember you can only change the shape positions, not their number when updating a polygon.
  33282. */
  33283. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33284. var options = {
  33285. shape: shape,
  33286. holes: holes,
  33287. updatable: updatable,
  33288. sideOrientation: sideOrientation
  33289. };
  33290. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33291. };
  33292. /**
  33293. * Creates an extruded polygon mesh, with depth in the Y direction.
  33294. * Please consider using the same method from the MeshBuilder class instead.
  33295. */
  33296. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33297. var options = {
  33298. shape: shape,
  33299. holes: holes,
  33300. depth: depth,
  33301. updatable: updatable,
  33302. sideOrientation: sideOrientation
  33303. };
  33304. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33305. };
  33306. /**
  33307. * Creates an extruded shape mesh.
  33308. * 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.
  33309. * Please consider using the same method from the MeshBuilder class instead.
  33310. *
  33311. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33312. * 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
  33313. * extruded along the Z axis.
  33314. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33315. * 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.
  33316. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33317. * 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
  33318. * 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
  33319. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33320. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33321. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33323. */
  33324. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33325. if (scene === void 0) { scene = null; }
  33326. var options = {
  33327. shape: shape,
  33328. path: path,
  33329. scale: scale,
  33330. rotation: rotation,
  33331. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33332. sideOrientation: sideOrientation,
  33333. instance: instance,
  33334. updatable: updatable
  33335. };
  33336. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33337. };
  33338. /**
  33339. * Creates an custom extruded shape mesh.
  33340. * 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.
  33341. * Please consider using the same method from the MeshBuilder class instead.
  33342. *
  33343. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33344. * 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
  33345. * extruded along the Z axis.
  33346. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33347. * 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
  33348. * and the distance of this point from the begining of the path :
  33349. * ```javascript
  33350. * var rotationFunction = function(i, distance) {
  33351. * // do things
  33352. * return rotationValue; }
  33353. * ```
  33354. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33355. * 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
  33356. * and the distance of this point from the begining of the path :
  33357. * ```javascript
  33358. * var scaleFunction = function(i, distance) {
  33359. * // do things
  33360. * return scaleValue;}
  33361. * ```
  33362. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33363. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33364. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33365. * 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
  33366. * 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
  33367. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33368. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33369. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33370. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33371. */
  33372. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33373. var options = {
  33374. shape: shape,
  33375. path: path,
  33376. scaleFunction: scaleFunction,
  33377. rotationFunction: rotationFunction,
  33378. ribbonCloseArray: ribbonCloseArray,
  33379. ribbonClosePath: ribbonClosePath,
  33380. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33381. sideOrientation: sideOrientation,
  33382. instance: instance,
  33383. updatable: updatable
  33384. };
  33385. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33386. };
  33387. /**
  33388. * Creates lathe mesh.
  33389. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33390. * Please consider using the same method from the MeshBuilder class instead.
  33391. * 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
  33392. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33393. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33394. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33395. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33396. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33397. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33398. */
  33399. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33400. var options = {
  33401. shape: shape,
  33402. radius: radius,
  33403. tessellation: tessellation,
  33404. sideOrientation: sideOrientation,
  33405. updatable: updatable
  33406. };
  33407. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33408. };
  33409. /**
  33410. * Creates a plane mesh.
  33411. * Please consider using the same method from the MeshBuilder class instead.
  33412. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33413. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33414. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33415. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33416. */
  33417. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33418. var options = {
  33419. size: size,
  33420. width: size,
  33421. height: size,
  33422. sideOrientation: sideOrientation,
  33423. updatable: updatable
  33424. };
  33425. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33426. };
  33427. /**
  33428. * Creates a ground mesh.
  33429. * Please consider using the same method from the MeshBuilder class instead.
  33430. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33431. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33433. */
  33434. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33435. var options = {
  33436. width: width,
  33437. height: height,
  33438. subdivisions: subdivisions,
  33439. updatable: updatable
  33440. };
  33441. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33442. };
  33443. /**
  33444. * Creates a tiled ground mesh.
  33445. * Please consider using the same method from the MeshBuilder class instead.
  33446. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33447. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33448. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33449. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33450. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33451. * numbers of subdivisions on the ground width and height of each tile.
  33452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33453. */
  33454. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33455. var options = {
  33456. xmin: xmin,
  33457. zmin: zmin,
  33458. xmax: xmax,
  33459. zmax: zmax,
  33460. subdivisions: subdivisions,
  33461. precision: precision,
  33462. updatable: updatable
  33463. };
  33464. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33465. };
  33466. /**
  33467. * Creates a ground mesh from a height map.
  33468. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33469. * Please consider using the same method from the MeshBuilder class instead.
  33470. * The parameter `url` sets the URL of the height map image resource.
  33471. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33472. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33473. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33474. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33475. * 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).
  33476. * This function is passed the newly built mesh :
  33477. * ```javascript
  33478. * function(mesh) { // do things
  33479. * return; }
  33480. * ```
  33481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33482. */
  33483. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33484. var options = {
  33485. width: width,
  33486. height: height,
  33487. subdivisions: subdivisions,
  33488. minHeight: minHeight,
  33489. maxHeight: maxHeight,
  33490. updatable: updatable,
  33491. onReady: onReady
  33492. };
  33493. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33494. };
  33495. /**
  33496. * Creates a tube mesh.
  33497. * 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.
  33498. * Please consider using the same method from the MeshBuilder class instead.
  33499. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33500. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33501. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33502. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33503. * 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.
  33504. * It must return a radius value (positive float) :
  33505. * ```javascript
  33506. * var radiusFunction = function(i, distance) {
  33507. * // do things
  33508. * return radius; }
  33509. * ```
  33510. * 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
  33511. * 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
  33512. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33513. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33515. */
  33516. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33517. var options = {
  33518. path: path,
  33519. radius: radius,
  33520. tessellation: tessellation,
  33521. radiusFunction: radiusFunction,
  33522. arc: 1,
  33523. cap: cap,
  33524. updatable: updatable,
  33525. sideOrientation: sideOrientation,
  33526. instance: instance
  33527. };
  33528. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33529. };
  33530. /**
  33531. * Creates a polyhedron mesh.
  33532. * Please consider using the same method from the MeshBuilder class instead.
  33533. * 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
  33534. * to choose the wanted type.
  33535. * The parameter `size` (positive float, default 1) sets the polygon size.
  33536. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33537. * 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`.
  33538. * 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
  33539. * 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)`).
  33540. * 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
  33541. * 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.
  33542. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33543. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33544. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33545. */
  33546. Mesh.CreatePolyhedron = function (name, options, scene) {
  33547. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33548. };
  33549. /**
  33550. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33551. * Please consider using the same method from the MeshBuilder class instead.
  33552. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33553. * 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`).
  33554. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33555. * 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.
  33556. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33557. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33558. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33559. */
  33560. Mesh.CreateIcoSphere = function (name, options, scene) {
  33561. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33562. };
  33563. /**
  33564. * Creates a decal mesh.
  33565. * Please consider using the same method from the MeshBuilder class instead.
  33566. * 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.
  33567. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33568. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33569. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33570. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33571. */
  33572. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33573. var options = {
  33574. position: position,
  33575. normal: normal,
  33576. size: size,
  33577. angle: angle
  33578. };
  33579. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33580. };
  33581. // Skeletons
  33582. /**
  33583. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33584. */
  33585. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33586. if (!this._sourcePositions) {
  33587. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33588. if (!source) {
  33589. return this._sourcePositions;
  33590. }
  33591. this._sourcePositions = new Float32Array(source);
  33592. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33593. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33594. }
  33595. }
  33596. return this._sourcePositions;
  33597. };
  33598. /**
  33599. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33600. */
  33601. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33602. if (!this._sourceNormals) {
  33603. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33604. if (!source) {
  33605. return this._sourceNormals;
  33606. }
  33607. this._sourceNormals = new Float32Array(source);
  33608. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33609. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33610. }
  33611. }
  33612. return this._sourceNormals;
  33613. };
  33614. /**
  33615. * Updates the vertex buffer by applying transformation from the bones.
  33616. * Returns the Mesh.
  33617. *
  33618. * @param {skeleton} skeleton to apply
  33619. */
  33620. Mesh.prototype.applySkeleton = function (skeleton) {
  33621. if (!this.geometry) {
  33622. return this;
  33623. }
  33624. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33625. return this;
  33626. }
  33627. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33628. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33629. return this;
  33630. }
  33631. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33632. return this;
  33633. }
  33634. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33635. return this;
  33636. }
  33637. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33638. return this;
  33639. }
  33640. if (!this._sourcePositions) {
  33641. var submeshes = this.subMeshes.slice();
  33642. this.setPositionsForCPUSkinning();
  33643. this.subMeshes = submeshes;
  33644. }
  33645. if (!this._sourceNormals) {
  33646. this.setNormalsForCPUSkinning();
  33647. }
  33648. // positionsData checks for not being Float32Array will only pass at most once
  33649. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33650. if (!positionsData) {
  33651. return this;
  33652. }
  33653. if (!(positionsData instanceof Float32Array)) {
  33654. positionsData = new Float32Array(positionsData);
  33655. }
  33656. // normalsData checks for not being Float32Array will only pass at most once
  33657. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33658. if (!normalsData) {
  33659. return this;
  33660. }
  33661. if (!(normalsData instanceof Float32Array)) {
  33662. normalsData = new Float32Array(normalsData);
  33663. }
  33664. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33665. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33666. if (!matricesWeightsData || !matricesIndicesData) {
  33667. return this;
  33668. }
  33669. var needExtras = this.numBoneInfluencers > 4;
  33670. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33671. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33672. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33673. var tempVector3 = BABYLON.Vector3.Zero();
  33674. var finalMatrix = new BABYLON.Matrix();
  33675. var tempMatrix = new BABYLON.Matrix();
  33676. var matWeightIdx = 0;
  33677. var inf;
  33678. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33679. var weight;
  33680. for (inf = 0; inf < 4; inf++) {
  33681. weight = matricesWeightsData[matWeightIdx + inf];
  33682. if (weight > 0) {
  33683. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33684. finalMatrix.addToSelf(tempMatrix);
  33685. }
  33686. else
  33687. break;
  33688. }
  33689. if (needExtras) {
  33690. for (inf = 0; inf < 4; inf++) {
  33691. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33692. if (weight > 0) {
  33693. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33694. finalMatrix.addToSelf(tempMatrix);
  33695. }
  33696. else
  33697. break;
  33698. }
  33699. }
  33700. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33701. tempVector3.toArray(positionsData, index);
  33702. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33703. tempVector3.toArray(normalsData, index);
  33704. finalMatrix.reset();
  33705. }
  33706. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33707. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33708. return this;
  33709. };
  33710. // Tools
  33711. /**
  33712. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33713. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33714. */
  33715. Mesh.MinMax = function (meshes) {
  33716. var minVector = null;
  33717. var maxVector = null;
  33718. meshes.forEach(function (mesh, index, array) {
  33719. var boundingInfo = mesh.getBoundingInfo();
  33720. var boundingBox = boundingInfo.boundingBox;
  33721. if (!minVector || !maxVector) {
  33722. minVector = boundingBox.minimumWorld;
  33723. maxVector = boundingBox.maximumWorld;
  33724. }
  33725. else {
  33726. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33727. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33728. }
  33729. });
  33730. if (!minVector || !maxVector) {
  33731. return {
  33732. min: BABYLON.Vector3.Zero(),
  33733. max: BABYLON.Vector3.Zero()
  33734. };
  33735. }
  33736. return {
  33737. min: minVector,
  33738. max: maxVector
  33739. };
  33740. };
  33741. /**
  33742. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33743. */
  33744. Mesh.Center = function (meshesOrMinMaxVector) {
  33745. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33746. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33747. };
  33748. /**
  33749. * Merge the array of meshes into a single mesh for performance reasons.
  33750. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33751. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33752. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33753. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33754. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33755. */
  33756. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33757. if (disposeSource === void 0) { disposeSource = true; }
  33758. var index;
  33759. if (!allow32BitsIndices) {
  33760. var totalVertices = 0;
  33761. // Counting vertices
  33762. for (index = 0; index < meshes.length; index++) {
  33763. if (meshes[index]) {
  33764. totalVertices += meshes[index].getTotalVertices();
  33765. if (totalVertices > 65536) {
  33766. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33767. return null;
  33768. }
  33769. }
  33770. }
  33771. }
  33772. // Merge
  33773. var vertexData = null;
  33774. var otherVertexData;
  33775. var indiceArray = new Array();
  33776. var source = null;
  33777. for (index = 0; index < meshes.length; index++) {
  33778. if (meshes[index]) {
  33779. meshes[index].computeWorldMatrix(true);
  33780. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33781. otherVertexData.transform(meshes[index].getWorldMatrix());
  33782. if (vertexData) {
  33783. vertexData.merge(otherVertexData);
  33784. }
  33785. else {
  33786. vertexData = otherVertexData;
  33787. source = meshes[index];
  33788. }
  33789. if (subdivideWithSubMeshes) {
  33790. indiceArray.push(meshes[index].getTotalIndices());
  33791. }
  33792. }
  33793. }
  33794. source = source;
  33795. if (!meshSubclass) {
  33796. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33797. }
  33798. vertexData.applyToMesh(meshSubclass);
  33799. // Setting properties
  33800. meshSubclass.material = source.material;
  33801. meshSubclass.checkCollisions = source.checkCollisions;
  33802. // Cleaning
  33803. if (disposeSource) {
  33804. for (index = 0; index < meshes.length; index++) {
  33805. if (meshes[index]) {
  33806. meshes[index].dispose();
  33807. }
  33808. }
  33809. }
  33810. // Subdivide
  33811. if (subdivideWithSubMeshes) {
  33812. //-- Suppresions du submesh global
  33813. meshSubclass.releaseSubMeshes();
  33814. index = 0;
  33815. var offset = 0;
  33816. //-- aplique la subdivision en fonction du tableau d'indices
  33817. while (index < indiceArray.length) {
  33818. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33819. offset += indiceArray[index];
  33820. index++;
  33821. }
  33822. }
  33823. return meshSubclass;
  33824. };
  33825. // Consts
  33826. Mesh._FRONTSIDE = 0;
  33827. Mesh._BACKSIDE = 1;
  33828. Mesh._DOUBLESIDE = 2;
  33829. Mesh._DEFAULTSIDE = 0;
  33830. Mesh._NO_CAP = 0;
  33831. Mesh._CAP_START = 1;
  33832. Mesh._CAP_END = 2;
  33833. Mesh._CAP_ALL = 3;
  33834. return Mesh;
  33835. }(BABYLON.AbstractMesh));
  33836. BABYLON.Mesh = Mesh;
  33837. })(BABYLON || (BABYLON = {}));
  33838. //# sourceMappingURL=babylon.mesh.js.map
  33839. var BABYLON;
  33840. (function (BABYLON) {
  33841. var BaseSubMesh = /** @class */ (function () {
  33842. function BaseSubMesh() {
  33843. }
  33844. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33845. get: function () {
  33846. return this._materialEffect;
  33847. },
  33848. enumerable: true,
  33849. configurable: true
  33850. });
  33851. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33852. if (defines === void 0) { defines = null; }
  33853. if (this._materialEffect === effect) {
  33854. if (!effect) {
  33855. this._materialDefines = null;
  33856. }
  33857. return;
  33858. }
  33859. this._materialDefines = defines;
  33860. this._materialEffect = effect;
  33861. };
  33862. return BaseSubMesh;
  33863. }());
  33864. BABYLON.BaseSubMesh = BaseSubMesh;
  33865. var SubMesh = /** @class */ (function (_super) {
  33866. __extends(SubMesh, _super);
  33867. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33868. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33869. var _this = _super.call(this) || this;
  33870. _this.materialIndex = materialIndex;
  33871. _this.verticesStart = verticesStart;
  33872. _this.verticesCount = verticesCount;
  33873. _this.indexStart = indexStart;
  33874. _this.indexCount = indexCount;
  33875. _this._renderId = 0;
  33876. _this._mesh = mesh;
  33877. _this._renderingMesh = renderingMesh || mesh;
  33878. mesh.subMeshes.push(_this);
  33879. _this._trianglePlanes = [];
  33880. _this._id = mesh.subMeshes.length - 1;
  33881. if (createBoundingBox) {
  33882. _this.refreshBoundingInfo();
  33883. mesh.computeWorldMatrix(true);
  33884. }
  33885. return _this;
  33886. }
  33887. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33888. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33889. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33890. };
  33891. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33892. get: function () {
  33893. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33894. },
  33895. enumerable: true,
  33896. configurable: true
  33897. });
  33898. /**
  33899. * Returns the submesh BoudingInfo object.
  33900. */
  33901. SubMesh.prototype.getBoundingInfo = function () {
  33902. if (this.IsGlobal) {
  33903. return this._mesh.getBoundingInfo();
  33904. }
  33905. return this._boundingInfo;
  33906. };
  33907. /**
  33908. * Sets the submesh BoundingInfo.
  33909. * Return the SubMesh.
  33910. */
  33911. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33912. this._boundingInfo = boundingInfo;
  33913. return this;
  33914. };
  33915. /**
  33916. * Returns the mesh of the current submesh.
  33917. */
  33918. SubMesh.prototype.getMesh = function () {
  33919. return this._mesh;
  33920. };
  33921. /**
  33922. * Returns the rendering mesh of the submesh.
  33923. */
  33924. SubMesh.prototype.getRenderingMesh = function () {
  33925. return this._renderingMesh;
  33926. };
  33927. /**
  33928. * Returns the submesh material.
  33929. */
  33930. SubMesh.prototype.getMaterial = function () {
  33931. var rootMaterial = this._renderingMesh.material;
  33932. if (rootMaterial === null || rootMaterial === undefined) {
  33933. return this._mesh.getScene().defaultMaterial;
  33934. }
  33935. else if (rootMaterial.getSubMaterial) {
  33936. var multiMaterial = rootMaterial;
  33937. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33938. if (this._currentMaterial !== effectiveMaterial) {
  33939. this._currentMaterial = effectiveMaterial;
  33940. this._materialDefines = null;
  33941. }
  33942. return effectiveMaterial;
  33943. }
  33944. return rootMaterial;
  33945. };
  33946. // Methods
  33947. /**
  33948. * Sets a new updated BoundingInfo object to the submesh.
  33949. * Returns the SubMesh.
  33950. */
  33951. SubMesh.prototype.refreshBoundingInfo = function () {
  33952. this._lastColliderWorldVertices = null;
  33953. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33954. return this;
  33955. }
  33956. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33957. if (!data) {
  33958. this._boundingInfo = this._mesh.getBoundingInfo();
  33959. return this;
  33960. }
  33961. var indices = this._renderingMesh.getIndices();
  33962. var extend;
  33963. //is this the only submesh?
  33964. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33965. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33966. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33967. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33968. }
  33969. else {
  33970. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33971. }
  33972. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33973. return this;
  33974. };
  33975. SubMesh.prototype._checkCollision = function (collider) {
  33976. var boundingInfo = this.getBoundingInfo();
  33977. return boundingInfo._checkCollision(collider);
  33978. };
  33979. /**
  33980. * Updates the submesh BoundingInfo.
  33981. * Returns the Submesh.
  33982. */
  33983. SubMesh.prototype.updateBoundingInfo = function (world) {
  33984. var boundingInfo = this.getBoundingInfo();
  33985. if (!boundingInfo) {
  33986. this.refreshBoundingInfo();
  33987. boundingInfo = this.getBoundingInfo();
  33988. }
  33989. boundingInfo.update(world);
  33990. return this;
  33991. };
  33992. /**
  33993. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33994. * Boolean returned.
  33995. */
  33996. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33997. var boundingInfo = this.getBoundingInfo();
  33998. if (!boundingInfo) {
  33999. return false;
  34000. }
  34001. return boundingInfo.isInFrustum(frustumPlanes);
  34002. };
  34003. /**
  34004. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34005. * Boolean returned.
  34006. */
  34007. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34008. var boundingInfo = this.getBoundingInfo();
  34009. if (!boundingInfo) {
  34010. return false;
  34011. }
  34012. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34013. };
  34014. /**
  34015. * Renders the submesh.
  34016. * Returns it.
  34017. */
  34018. SubMesh.prototype.render = function (enableAlphaMode) {
  34019. this._renderingMesh.render(this, enableAlphaMode);
  34020. return this;
  34021. };
  34022. /**
  34023. * Returns a new Index Buffer.
  34024. * Type returned : WebGLBuffer.
  34025. */
  34026. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34027. if (!this._linesIndexBuffer) {
  34028. var linesIndices = [];
  34029. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34030. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34031. }
  34032. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34033. this.linesIndexCount = linesIndices.length;
  34034. }
  34035. return this._linesIndexBuffer;
  34036. };
  34037. /**
  34038. * True is the passed Ray intersects the submesh bounding box.
  34039. * Boolean returned.
  34040. */
  34041. SubMesh.prototype.canIntersects = function (ray) {
  34042. var boundingInfo = this.getBoundingInfo();
  34043. if (!boundingInfo) {
  34044. return false;
  34045. }
  34046. return ray.intersectsBox(boundingInfo.boundingBox);
  34047. };
  34048. /**
  34049. * Returns an object IntersectionInfo.
  34050. */
  34051. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34052. var intersectInfo = null;
  34053. var material = this.getMaterial();
  34054. if (!material) {
  34055. return null;
  34056. }
  34057. switch (material.fillMode) {
  34058. case BABYLON.Material.PointListDrawMode:
  34059. case BABYLON.Material.LineListDrawMode:
  34060. case BABYLON.Material.LineLoopDrawMode:
  34061. case BABYLON.Material.LineStripDrawMode:
  34062. case BABYLON.Material.TriangleFanDrawMode:
  34063. case BABYLON.Material.TriangleStripDrawMode:
  34064. return null;
  34065. }
  34066. // LineMesh first as it's also a Mesh...
  34067. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34068. var lineMesh = this._mesh;
  34069. // Line test
  34070. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34071. var p0 = positions[indices[index]];
  34072. var p1 = positions[indices[index + 1]];
  34073. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34074. if (length < 0) {
  34075. continue;
  34076. }
  34077. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34078. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34079. if (fastCheck) {
  34080. break;
  34081. }
  34082. }
  34083. }
  34084. }
  34085. else {
  34086. // Triangles test
  34087. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34088. var p0 = positions[indices[index]];
  34089. var p1 = positions[indices[index + 1]];
  34090. var p2 = positions[indices[index + 2]];
  34091. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34092. if (currentIntersectInfo) {
  34093. if (currentIntersectInfo.distance < 0) {
  34094. continue;
  34095. }
  34096. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34097. intersectInfo = currentIntersectInfo;
  34098. intersectInfo.faceId = index / 3;
  34099. if (fastCheck) {
  34100. break;
  34101. }
  34102. }
  34103. }
  34104. }
  34105. }
  34106. return intersectInfo;
  34107. };
  34108. SubMesh.prototype._rebuild = function () {
  34109. if (this._linesIndexBuffer) {
  34110. this._linesIndexBuffer = null;
  34111. }
  34112. };
  34113. // Clone
  34114. /**
  34115. * Creates a new Submesh from the passed Mesh.
  34116. */
  34117. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34118. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34119. if (!this.IsGlobal) {
  34120. var boundingInfo = this.getBoundingInfo();
  34121. if (!boundingInfo) {
  34122. return result;
  34123. }
  34124. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34125. }
  34126. return result;
  34127. };
  34128. // Dispose
  34129. /**
  34130. * Disposes the Submesh.
  34131. * Returns nothing.
  34132. */
  34133. SubMesh.prototype.dispose = function () {
  34134. if (this._linesIndexBuffer) {
  34135. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34136. this._linesIndexBuffer = null;
  34137. }
  34138. // Remove from mesh
  34139. var index = this._mesh.subMeshes.indexOf(this);
  34140. this._mesh.subMeshes.splice(index, 1);
  34141. };
  34142. // Statics
  34143. /**
  34144. * Creates a new Submesh from the passed parameters :
  34145. * - materialIndex (integer) : the index of the main mesh material.
  34146. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34147. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34148. * - mesh (Mesh) : the main mesh to create the submesh from.
  34149. * - renderingMesh (optional Mesh) : rendering mesh.
  34150. */
  34151. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34152. var minVertexIndex = Number.MAX_VALUE;
  34153. var maxVertexIndex = -Number.MAX_VALUE;
  34154. renderingMesh = (renderingMesh || mesh);
  34155. var indices = renderingMesh.getIndices();
  34156. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34157. var vertexIndex = indices[index];
  34158. if (vertexIndex < minVertexIndex)
  34159. minVertexIndex = vertexIndex;
  34160. if (vertexIndex > maxVertexIndex)
  34161. maxVertexIndex = vertexIndex;
  34162. }
  34163. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34164. };
  34165. return SubMesh;
  34166. }(BaseSubMesh));
  34167. BABYLON.SubMesh = SubMesh;
  34168. })(BABYLON || (BABYLON = {}));
  34169. //# sourceMappingURL=babylon.subMesh.js.map
  34170. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34171. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34172. s = arguments[i];
  34173. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34174. t[p] = s[p];
  34175. }
  34176. return t;
  34177. };
  34178. var BABYLON;
  34179. (function (BABYLON) {
  34180. /**
  34181. * Manages the defines for the Material
  34182. */
  34183. var MaterialDefines = /** @class */ (function () {
  34184. function MaterialDefines() {
  34185. this._isDirty = true;
  34186. /** @hidden */
  34187. this._areLightsDirty = true;
  34188. /** @hidden */
  34189. this._areAttributesDirty = true;
  34190. /** @hidden */
  34191. this._areTexturesDirty = true;
  34192. /** @hidden */
  34193. this._areFresnelDirty = true;
  34194. /** @hidden */
  34195. this._areMiscDirty = true;
  34196. /** @hidden */
  34197. this._areImageProcessingDirty = true;
  34198. /** @hidden */
  34199. this._normals = false;
  34200. /** @hidden */
  34201. this._uvs = false;
  34202. /** @hidden */
  34203. this._needNormals = false;
  34204. /** @hidden */
  34205. this._needUVs = false;
  34206. }
  34207. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34208. /**
  34209. * Specifies if the material needs to be re-calculated
  34210. */
  34211. get: function () {
  34212. return this._isDirty;
  34213. },
  34214. enumerable: true,
  34215. configurable: true
  34216. });
  34217. /**
  34218. * Marks the material to indicate that it has been re-calculated
  34219. */
  34220. MaterialDefines.prototype.markAsProcessed = function () {
  34221. this._isDirty = false;
  34222. this._areAttributesDirty = false;
  34223. this._areTexturesDirty = false;
  34224. this._areFresnelDirty = false;
  34225. this._areLightsDirty = false;
  34226. this._areMiscDirty = false;
  34227. this._areImageProcessingDirty = false;
  34228. };
  34229. /**
  34230. * Marks the material to indicate that it needs to be re-calculated
  34231. */
  34232. MaterialDefines.prototype.markAsUnprocessed = function () {
  34233. this._isDirty = true;
  34234. };
  34235. /**
  34236. * Marks the material to indicate all of its defines need to be re-calculated
  34237. */
  34238. MaterialDefines.prototype.markAllAsDirty = function () {
  34239. this._areTexturesDirty = true;
  34240. this._areAttributesDirty = true;
  34241. this._areLightsDirty = true;
  34242. this._areFresnelDirty = true;
  34243. this._areMiscDirty = true;
  34244. this._areImageProcessingDirty = true;
  34245. this._isDirty = true;
  34246. };
  34247. /**
  34248. * Marks the material to indicate that image processing needs to be re-calculated
  34249. */
  34250. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34251. this._areImageProcessingDirty = true;
  34252. this._isDirty = true;
  34253. };
  34254. /**
  34255. * Marks the material to indicate the lights need to be re-calculated
  34256. */
  34257. MaterialDefines.prototype.markAsLightDirty = function () {
  34258. this._areLightsDirty = true;
  34259. this._isDirty = true;
  34260. };
  34261. /**
  34262. * Marks the attribute state as changed
  34263. */
  34264. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34265. this._areAttributesDirty = true;
  34266. this._isDirty = true;
  34267. };
  34268. /**
  34269. * Marks the texture state as changed
  34270. */
  34271. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34272. this._areTexturesDirty = true;
  34273. this._isDirty = true;
  34274. };
  34275. /**
  34276. * Marks the fresnel state as changed
  34277. */
  34278. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34279. this._areFresnelDirty = true;
  34280. this._isDirty = true;
  34281. };
  34282. /**
  34283. * Marks the misc state as changed
  34284. */
  34285. MaterialDefines.prototype.markAsMiscDirty = function () {
  34286. this._areMiscDirty = true;
  34287. this._isDirty = true;
  34288. };
  34289. /**
  34290. * Rebuilds the material defines
  34291. */
  34292. MaterialDefines.prototype.rebuild = function () {
  34293. if (this._keys) {
  34294. delete this._keys;
  34295. }
  34296. this._keys = [];
  34297. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34298. var key = _a[_i];
  34299. if (key[0] === "_") {
  34300. continue;
  34301. }
  34302. this._keys.push(key);
  34303. }
  34304. };
  34305. /**
  34306. * Specifies if two material defines are equal
  34307. * @param other - A material define instance to compare to
  34308. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34309. */
  34310. MaterialDefines.prototype.isEqual = function (other) {
  34311. if (this._keys.length !== other._keys.length) {
  34312. return false;
  34313. }
  34314. for (var index = 0; index < this._keys.length; index++) {
  34315. var prop = this._keys[index];
  34316. if (this[prop] !== other[prop]) {
  34317. return false;
  34318. }
  34319. }
  34320. return true;
  34321. };
  34322. /**
  34323. * Clones this instance's defines to another instance
  34324. * @param other - material defines to clone values to
  34325. */
  34326. MaterialDefines.prototype.cloneTo = function (other) {
  34327. if (this._keys.length !== other._keys.length) {
  34328. other._keys = this._keys.slice(0);
  34329. }
  34330. for (var index = 0; index < this._keys.length; index++) {
  34331. var prop = this._keys[index];
  34332. other[prop] = this[prop];
  34333. }
  34334. };
  34335. /**
  34336. * Resets the material define values
  34337. */
  34338. MaterialDefines.prototype.reset = function () {
  34339. for (var index = 0; index < this._keys.length; index++) {
  34340. var prop = this._keys[index];
  34341. var type = typeof this[prop];
  34342. switch (type) {
  34343. case "number":
  34344. this[prop] = 0;
  34345. break;
  34346. case "string":
  34347. this[prop] = "";
  34348. break;
  34349. default:
  34350. this[prop] = false;
  34351. break;
  34352. }
  34353. }
  34354. };
  34355. /**
  34356. * Converts the material define values to a string
  34357. * @returns - String of material define information
  34358. */
  34359. MaterialDefines.prototype.toString = function () {
  34360. var result = "";
  34361. for (var index = 0; index < this._keys.length; index++) {
  34362. var prop = this._keys[index];
  34363. var value = this[prop];
  34364. var type = typeof value;
  34365. switch (type) {
  34366. case "number":
  34367. case "string":
  34368. result += "#define " + prop + " " + value + "\n";
  34369. break;
  34370. default:
  34371. if (value) {
  34372. result += "#define " + prop + "\n";
  34373. }
  34374. break;
  34375. }
  34376. }
  34377. return result;
  34378. };
  34379. return MaterialDefines;
  34380. }());
  34381. BABYLON.MaterialDefines = MaterialDefines;
  34382. /**
  34383. * Base class for the main features of a material in Babylon.js
  34384. */
  34385. var Material = /** @class */ (function () {
  34386. /**
  34387. * Creates a material instance
  34388. * @param name defines the name of the material
  34389. * @param scene defines the scene to reference
  34390. * @param doNotAdd specifies if the material should be added to the scene
  34391. */
  34392. function Material(name, scene, doNotAdd) {
  34393. /**
  34394. * Specifies if the ready state should be checked on each call
  34395. */
  34396. this.checkReadyOnEveryCall = false;
  34397. /**
  34398. * Specifies if the ready state should be checked once
  34399. */
  34400. this.checkReadyOnlyOnce = false;
  34401. /**
  34402. * The state of the material
  34403. */
  34404. this.state = "";
  34405. /**
  34406. * The alpha value of the material
  34407. */
  34408. this._alpha = 1.0;
  34409. /**
  34410. * Specifies if back face culling is enabled
  34411. */
  34412. this._backFaceCulling = true;
  34413. /**
  34414. * Specifies if the material should be serialized
  34415. */
  34416. this.doNotSerialize = false;
  34417. /**
  34418. * Specifies if the effect should be stored on sub meshes
  34419. */
  34420. this.storeEffectOnSubMeshes = false;
  34421. /**
  34422. * An event triggered when the material is disposed
  34423. */
  34424. this.onDisposeObservable = new BABYLON.Observable();
  34425. /**
  34426. * An event triggered when the material is bound
  34427. */
  34428. this.onBindObservable = new BABYLON.Observable();
  34429. /**
  34430. * An event triggered when the material is unbound
  34431. */
  34432. this.onUnBindObservable = new BABYLON.Observable();
  34433. /**
  34434. * Stores the value of the alpha mode
  34435. */
  34436. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34437. /**
  34438. * Stores the state of the need depth pre-pass value
  34439. */
  34440. this._needDepthPrePass = false;
  34441. /**
  34442. * Specifies if depth writing should be disabled
  34443. */
  34444. this.disableDepthWrite = false;
  34445. /**
  34446. * Specifies if depth writing should be forced
  34447. */
  34448. this.forceDepthWrite = false;
  34449. /**
  34450. * Specifies if there should be a separate pass for culling
  34451. */
  34452. this.separateCullingPass = false;
  34453. /**
  34454. * Stores the state specifing if fog should be enabled
  34455. */
  34456. this._fogEnabled = true;
  34457. /**
  34458. * Stores the size of points
  34459. */
  34460. this.pointSize = 1.0;
  34461. /**
  34462. * Stores the z offset value
  34463. */
  34464. this.zOffset = 0;
  34465. /**
  34466. * Specifies if the material was previously ready
  34467. */
  34468. this._wasPreviouslyReady = false;
  34469. /**
  34470. * Stores the fill mode state
  34471. */
  34472. this._fillMode = Material.TriangleFillMode;
  34473. this.name = name;
  34474. this.id = name || BABYLON.Tools.RandomId();
  34475. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34476. if (this._scene.useRightHandedSystem) {
  34477. this.sideOrientation = Material.ClockWiseSideOrientation;
  34478. }
  34479. else {
  34480. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34481. }
  34482. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34483. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34484. if (!doNotAdd) {
  34485. this._scene.materials.push(this);
  34486. }
  34487. }
  34488. Object.defineProperty(Material, "TriangleFillMode", {
  34489. /**
  34490. * Returns the triangle fill mode
  34491. */
  34492. get: function () {
  34493. return Material._TriangleFillMode;
  34494. },
  34495. enumerable: true,
  34496. configurable: true
  34497. });
  34498. Object.defineProperty(Material, "WireFrameFillMode", {
  34499. /**
  34500. * Returns the wireframe mode
  34501. */
  34502. get: function () {
  34503. return Material._WireFrameFillMode;
  34504. },
  34505. enumerable: true,
  34506. configurable: true
  34507. });
  34508. Object.defineProperty(Material, "PointFillMode", {
  34509. /**
  34510. * Returns the point fill mode
  34511. */
  34512. get: function () {
  34513. return Material._PointFillMode;
  34514. },
  34515. enumerable: true,
  34516. configurable: true
  34517. });
  34518. Object.defineProperty(Material, "PointListDrawMode", {
  34519. /**
  34520. * Returns the point list draw mode
  34521. */
  34522. get: function () {
  34523. return Material._PointListDrawMode;
  34524. },
  34525. enumerable: true,
  34526. configurable: true
  34527. });
  34528. Object.defineProperty(Material, "LineListDrawMode", {
  34529. /**
  34530. * Returns the line list draw mode
  34531. */
  34532. get: function () {
  34533. return Material._LineListDrawMode;
  34534. },
  34535. enumerable: true,
  34536. configurable: true
  34537. });
  34538. Object.defineProperty(Material, "LineLoopDrawMode", {
  34539. /**
  34540. * Returns the line loop draw mode
  34541. */
  34542. get: function () {
  34543. return Material._LineLoopDrawMode;
  34544. },
  34545. enumerable: true,
  34546. configurable: true
  34547. });
  34548. Object.defineProperty(Material, "LineStripDrawMode", {
  34549. /**
  34550. * Returns the line strip draw mode
  34551. */
  34552. get: function () {
  34553. return Material._LineStripDrawMode;
  34554. },
  34555. enumerable: true,
  34556. configurable: true
  34557. });
  34558. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34559. /**
  34560. * Returns the triangle strip draw mode
  34561. */
  34562. get: function () {
  34563. return Material._TriangleStripDrawMode;
  34564. },
  34565. enumerable: true,
  34566. configurable: true
  34567. });
  34568. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34569. /**
  34570. * Returns the triangle fan draw mode
  34571. */
  34572. get: function () {
  34573. return Material._TriangleFanDrawMode;
  34574. },
  34575. enumerable: true,
  34576. configurable: true
  34577. });
  34578. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34579. /**
  34580. * Returns the clock-wise side orientation
  34581. */
  34582. get: function () {
  34583. return Material._ClockWiseSideOrientation;
  34584. },
  34585. enumerable: true,
  34586. configurable: true
  34587. });
  34588. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34589. /**
  34590. * Returns the counter clock-wise side orientation
  34591. */
  34592. get: function () {
  34593. return Material._CounterClockWiseSideOrientation;
  34594. },
  34595. enumerable: true,
  34596. configurable: true
  34597. });
  34598. Object.defineProperty(Material, "TextureDirtyFlag", {
  34599. /**
  34600. * Returns the dirty texture flag value
  34601. */
  34602. get: function () {
  34603. return Material._TextureDirtyFlag;
  34604. },
  34605. enumerable: true,
  34606. configurable: true
  34607. });
  34608. Object.defineProperty(Material, "LightDirtyFlag", {
  34609. /**
  34610. * Returns the dirty light flag value
  34611. */
  34612. get: function () {
  34613. return Material._LightDirtyFlag;
  34614. },
  34615. enumerable: true,
  34616. configurable: true
  34617. });
  34618. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34619. /**
  34620. * Returns the dirty fresnel flag value
  34621. */
  34622. get: function () {
  34623. return Material._FresnelDirtyFlag;
  34624. },
  34625. enumerable: true,
  34626. configurable: true
  34627. });
  34628. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34629. /**
  34630. * Returns the dirty attributes flag value
  34631. */
  34632. get: function () {
  34633. return Material._AttributesDirtyFlag;
  34634. },
  34635. enumerable: true,
  34636. configurable: true
  34637. });
  34638. Object.defineProperty(Material, "MiscDirtyFlag", {
  34639. /**
  34640. * Returns the dirty misc flag value
  34641. */
  34642. get: function () {
  34643. return Material._MiscDirtyFlag;
  34644. },
  34645. enumerable: true,
  34646. configurable: true
  34647. });
  34648. Object.defineProperty(Material.prototype, "alpha", {
  34649. /**
  34650. * Gets the alpha value of the material
  34651. */
  34652. get: function () {
  34653. return this._alpha;
  34654. },
  34655. /**
  34656. * Sets the alpha value of the material
  34657. */
  34658. set: function (value) {
  34659. if (this._alpha === value) {
  34660. return;
  34661. }
  34662. this._alpha = value;
  34663. this.markAsDirty(Material.MiscDirtyFlag);
  34664. },
  34665. enumerable: true,
  34666. configurable: true
  34667. });
  34668. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34669. /**
  34670. * Gets the back-face culling state
  34671. */
  34672. get: function () {
  34673. return this._backFaceCulling;
  34674. },
  34675. /**
  34676. * Sets the back-face culling state
  34677. */
  34678. set: function (value) {
  34679. if (this._backFaceCulling === value) {
  34680. return;
  34681. }
  34682. this._backFaceCulling = value;
  34683. this.markAsDirty(Material.TextureDirtyFlag);
  34684. },
  34685. enumerable: true,
  34686. configurable: true
  34687. });
  34688. Object.defineProperty(Material.prototype, "onDispose", {
  34689. /**
  34690. * Called during a dispose event
  34691. */
  34692. set: function (callback) {
  34693. if (this._onDisposeObserver) {
  34694. this.onDisposeObservable.remove(this._onDisposeObserver);
  34695. }
  34696. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34697. },
  34698. enumerable: true,
  34699. configurable: true
  34700. });
  34701. Object.defineProperty(Material.prototype, "onBind", {
  34702. /**
  34703. * Called during a bind event
  34704. */
  34705. set: function (callback) {
  34706. if (this._onBindObserver) {
  34707. this.onBindObservable.remove(this._onBindObserver);
  34708. }
  34709. this._onBindObserver = this.onBindObservable.add(callback);
  34710. },
  34711. enumerable: true,
  34712. configurable: true
  34713. });
  34714. Object.defineProperty(Material.prototype, "alphaMode", {
  34715. /**
  34716. * Gets the value of the alpha mode
  34717. */
  34718. get: function () {
  34719. return this._alphaMode;
  34720. },
  34721. /**
  34722. * Sets the value of the alpha mode.
  34723. *
  34724. * | Value | Type | Description |
  34725. * | --- | --- | --- |
  34726. * | 0 | ALPHA_DISABLE | |
  34727. * | 1 | ALPHA_ADD | |
  34728. * | 2 | ALPHA_COMBINE | |
  34729. * | 3 | ALPHA_SUBTRACT | |
  34730. * | 4 | ALPHA_MULTIPLY | |
  34731. * | 5 | ALPHA_MAXIMIZED | |
  34732. * | 6 | ALPHA_ONEONE | |
  34733. * | 7 | ALPHA_PREMULTIPLIED | |
  34734. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34735. * | 9 | ALPHA_INTERPOLATE | |
  34736. * | 10 | ALPHA_SCREENMODE | |
  34737. *
  34738. */
  34739. set: function (value) {
  34740. if (this._alphaMode === value) {
  34741. return;
  34742. }
  34743. this._alphaMode = value;
  34744. this.markAsDirty(Material.TextureDirtyFlag);
  34745. },
  34746. enumerable: true,
  34747. configurable: true
  34748. });
  34749. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34750. /**
  34751. * Gets the depth pre-pass value
  34752. */
  34753. get: function () {
  34754. return this._needDepthPrePass;
  34755. },
  34756. /**
  34757. * Sets the need depth pre-pass value
  34758. */
  34759. set: function (value) {
  34760. if (this._needDepthPrePass === value) {
  34761. return;
  34762. }
  34763. this._needDepthPrePass = value;
  34764. if (this._needDepthPrePass) {
  34765. this.checkReadyOnEveryCall = true;
  34766. }
  34767. },
  34768. enumerable: true,
  34769. configurable: true
  34770. });
  34771. Object.defineProperty(Material.prototype, "fogEnabled", {
  34772. /**
  34773. * Gets the value of the fog enabled state
  34774. */
  34775. get: function () {
  34776. return this._fogEnabled;
  34777. },
  34778. /**
  34779. * Sets the state for enabling fog
  34780. */
  34781. set: function (value) {
  34782. if (this._fogEnabled === value) {
  34783. return;
  34784. }
  34785. this._fogEnabled = value;
  34786. this.markAsDirty(Material.MiscDirtyFlag);
  34787. },
  34788. enumerable: true,
  34789. configurable: true
  34790. });
  34791. Object.defineProperty(Material.prototype, "wireframe", {
  34792. /**
  34793. * Gets a value specifying if wireframe mode is enabled
  34794. */
  34795. get: function () {
  34796. switch (this._fillMode) {
  34797. case Material.WireFrameFillMode:
  34798. case Material.LineListDrawMode:
  34799. case Material.LineLoopDrawMode:
  34800. case Material.LineStripDrawMode:
  34801. return true;
  34802. }
  34803. return this._scene.forceWireframe;
  34804. },
  34805. /**
  34806. * Sets the state of wireframe mode
  34807. */
  34808. set: function (value) {
  34809. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34810. },
  34811. enumerable: true,
  34812. configurable: true
  34813. });
  34814. Object.defineProperty(Material.prototype, "pointsCloud", {
  34815. /**
  34816. * Gets the value specifying if point clouds are enabled
  34817. */
  34818. get: function () {
  34819. switch (this._fillMode) {
  34820. case Material.PointFillMode:
  34821. case Material.PointListDrawMode:
  34822. return true;
  34823. }
  34824. return this._scene.forcePointsCloud;
  34825. },
  34826. /**
  34827. * Sets the state of point cloud mode
  34828. */
  34829. set: function (value) {
  34830. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34831. },
  34832. enumerable: true,
  34833. configurable: true
  34834. });
  34835. Object.defineProperty(Material.prototype, "fillMode", {
  34836. /**
  34837. * Gets the material fill mode
  34838. */
  34839. get: function () {
  34840. return this._fillMode;
  34841. },
  34842. /**
  34843. * Sets the material fill mode
  34844. */
  34845. set: function (value) {
  34846. if (this._fillMode === value) {
  34847. return;
  34848. }
  34849. this._fillMode = value;
  34850. this.markAsDirty(Material.MiscDirtyFlag);
  34851. },
  34852. enumerable: true,
  34853. configurable: true
  34854. });
  34855. /**
  34856. * Returns a string representation of the current material
  34857. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34858. * @returns a string with material information
  34859. */
  34860. Material.prototype.toString = function (fullDetails) {
  34861. var ret = "Name: " + this.name;
  34862. if (fullDetails) {
  34863. }
  34864. return ret;
  34865. };
  34866. /**
  34867. * Gets the class name of the material
  34868. * @returns a string with the class name of the material
  34869. */
  34870. Material.prototype.getClassName = function () {
  34871. return "Material";
  34872. };
  34873. Object.defineProperty(Material.prototype, "isFrozen", {
  34874. /**
  34875. * Specifies if updates for the material been locked
  34876. */
  34877. get: function () {
  34878. return this.checkReadyOnlyOnce;
  34879. },
  34880. enumerable: true,
  34881. configurable: true
  34882. });
  34883. /**
  34884. * Locks updates for the material
  34885. */
  34886. Material.prototype.freeze = function () {
  34887. this.checkReadyOnlyOnce = true;
  34888. };
  34889. /**
  34890. * Unlocks updates for the material
  34891. */
  34892. Material.prototype.unfreeze = function () {
  34893. this.checkReadyOnlyOnce = false;
  34894. };
  34895. /**
  34896. * Specifies if the material is ready to be used
  34897. * @param mesh defines the mesh to check
  34898. * @param useInstances specifies if instances should be used
  34899. * @returns a boolean indicating if the material is ready to be used
  34900. */
  34901. Material.prototype.isReady = function (mesh, useInstances) {
  34902. return true;
  34903. };
  34904. /**
  34905. * Specifies that the submesh is ready to be used
  34906. * @param mesh defines the mesh to check
  34907. * @param subMesh defines which submesh to check
  34908. * @param useInstances specifies that instances should be used
  34909. * @returns a boolean indicating that the submesh is ready or not
  34910. */
  34911. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34912. return false;
  34913. };
  34914. /**
  34915. * Returns the material effect
  34916. * @returns the effect associated with the material
  34917. */
  34918. Material.prototype.getEffect = function () {
  34919. return this._effect;
  34920. };
  34921. /**
  34922. * Returns the current scene
  34923. * @returns a Scene
  34924. */
  34925. Material.prototype.getScene = function () {
  34926. return this._scene;
  34927. };
  34928. /**
  34929. * Specifies if the material will require alpha blending
  34930. * @returns a boolean specifying if alpha blending is needed
  34931. */
  34932. Material.prototype.needAlphaBlending = function () {
  34933. return (this.alpha < 1.0);
  34934. };
  34935. /**
  34936. * Specifies if the mesh will require alpha blending
  34937. * @param mesh defines the mesh to check
  34938. * @returns a boolean specifying if alpha blending is needed for the mesh
  34939. */
  34940. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34941. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34942. };
  34943. /**
  34944. * Specifies if this material should be rendered in alpha test mode
  34945. * @returns a boolean specifying if an alpha test is needed.
  34946. */
  34947. Material.prototype.needAlphaTesting = function () {
  34948. return false;
  34949. };
  34950. /**
  34951. * Gets the texture used for the alpha test
  34952. * @returns the texture to use for alpha testing
  34953. */
  34954. Material.prototype.getAlphaTestTexture = function () {
  34955. return null;
  34956. };
  34957. /**
  34958. * Marks the material to indicate that it needs to be re-calculated
  34959. */
  34960. Material.prototype.markDirty = function () {
  34961. this._wasPreviouslyReady = false;
  34962. };
  34963. /** @hidden */
  34964. Material.prototype._preBind = function (effect, overrideOrientation) {
  34965. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34966. var engine = this._scene.getEngine();
  34967. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34968. var reverse = orientation === Material.ClockWiseSideOrientation;
  34969. engine.enableEffect(effect ? effect : this._effect);
  34970. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34971. return reverse;
  34972. };
  34973. /**
  34974. * Binds the material to the mesh
  34975. * @param world defines the world transformation matrix
  34976. * @param mesh defines the mesh to bind the material to
  34977. */
  34978. Material.prototype.bind = function (world, mesh) {
  34979. };
  34980. /**
  34981. * Binds the submesh to the material
  34982. * @param world defines the world transformation matrix
  34983. * @param mesh defines the mesh containing the submesh
  34984. * @param subMesh defines the submesh to bind the material to
  34985. */
  34986. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34987. };
  34988. /**
  34989. * Binds the world matrix to the material
  34990. * @param world defines the world transformation matrix
  34991. */
  34992. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34993. };
  34994. /**
  34995. * Binds the scene's uniform buffer to the effect.
  34996. * @param effect defines the effect to bind to the scene uniform buffer
  34997. * @param sceneUbo defines the uniform buffer storing scene data
  34998. */
  34999. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35000. sceneUbo.bindToEffect(effect, "Scene");
  35001. };
  35002. /**
  35003. * Binds the view matrix to the effect
  35004. * @param effect defines the effect to bind the view matrix to
  35005. */
  35006. Material.prototype.bindView = function (effect) {
  35007. if (!this._useUBO) {
  35008. effect.setMatrix("view", this.getScene().getViewMatrix());
  35009. }
  35010. else {
  35011. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35012. }
  35013. };
  35014. /**
  35015. * Binds the view projection matrix to the effect
  35016. * @param effect defines the effect to bind the view projection matrix to
  35017. */
  35018. Material.prototype.bindViewProjection = function (effect) {
  35019. if (!this._useUBO) {
  35020. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35021. }
  35022. else {
  35023. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35024. }
  35025. };
  35026. /**
  35027. * Specifies if material alpha testing should be turned on for the mesh
  35028. * @param mesh defines the mesh to check
  35029. */
  35030. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35031. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35032. };
  35033. /**
  35034. * Processes to execute after binding the material to a mesh
  35035. * @param mesh defines the rendered mesh
  35036. */
  35037. Material.prototype._afterBind = function (mesh) {
  35038. this._scene._cachedMaterial = this;
  35039. if (mesh) {
  35040. this._scene._cachedVisibility = mesh.visibility;
  35041. }
  35042. else {
  35043. this._scene._cachedVisibility = 1;
  35044. }
  35045. if (mesh) {
  35046. this.onBindObservable.notifyObservers(mesh);
  35047. }
  35048. if (this.disableDepthWrite) {
  35049. var engine = this._scene.getEngine();
  35050. this._cachedDepthWriteState = engine.getDepthWrite();
  35051. engine.setDepthWrite(false);
  35052. }
  35053. };
  35054. /**
  35055. * Unbinds the material from the mesh
  35056. */
  35057. Material.prototype.unbind = function () {
  35058. this.onUnBindObservable.notifyObservers(this);
  35059. if (this.disableDepthWrite) {
  35060. var engine = this._scene.getEngine();
  35061. engine.setDepthWrite(this._cachedDepthWriteState);
  35062. }
  35063. };
  35064. /**
  35065. * Gets the active textures from the material
  35066. * @returns an array of textures
  35067. */
  35068. Material.prototype.getActiveTextures = function () {
  35069. return [];
  35070. };
  35071. /**
  35072. * Specifies if the material uses a texture
  35073. * @param texture defines the texture to check against the material
  35074. * @returns a boolean specifying if the material uses the texture
  35075. */
  35076. Material.prototype.hasTexture = function (texture) {
  35077. return false;
  35078. };
  35079. /**
  35080. * Makes a duplicate of the material, and gives it a new name
  35081. * @param name defines the new name for the duplicated material
  35082. * @returns the cloned material
  35083. */
  35084. Material.prototype.clone = function (name) {
  35085. return null;
  35086. };
  35087. /**
  35088. * Gets the meshes bound to the material
  35089. * @returns an array of meshes bound to the material
  35090. */
  35091. Material.prototype.getBindedMeshes = function () {
  35092. var result = new Array();
  35093. for (var index = 0; index < this._scene.meshes.length; index++) {
  35094. var mesh = this._scene.meshes[index];
  35095. if (mesh.material === this) {
  35096. result.push(mesh);
  35097. }
  35098. }
  35099. return result;
  35100. };
  35101. /**
  35102. * Force shader compilation
  35103. * @param mesh defines the mesh associated with this material
  35104. * @param onCompiled defines a function to execute once the material is compiled
  35105. * @param options defines the options to configure the compilation
  35106. */
  35107. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35108. var _this = this;
  35109. var localOptions = __assign({ clipPlane: false }, options);
  35110. var subMesh = new BABYLON.BaseSubMesh();
  35111. var scene = this.getScene();
  35112. var checkReady = function () {
  35113. if (!_this._scene || !_this._scene.getEngine()) {
  35114. return;
  35115. }
  35116. if (subMesh._materialDefines) {
  35117. subMesh._materialDefines._renderId = -1;
  35118. }
  35119. var clipPlaneState = scene.clipPlane;
  35120. if (localOptions.clipPlane) {
  35121. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35122. }
  35123. if (_this.storeEffectOnSubMeshes) {
  35124. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35125. if (onCompiled) {
  35126. onCompiled(_this);
  35127. }
  35128. }
  35129. else {
  35130. setTimeout(checkReady, 16);
  35131. }
  35132. }
  35133. else {
  35134. if (_this.isReady(mesh)) {
  35135. if (onCompiled) {
  35136. onCompiled(_this);
  35137. }
  35138. }
  35139. else {
  35140. setTimeout(checkReady, 16);
  35141. }
  35142. }
  35143. if (localOptions.clipPlane) {
  35144. scene.clipPlane = clipPlaneState;
  35145. }
  35146. };
  35147. checkReady();
  35148. };
  35149. /**
  35150. * Force shader compilation
  35151. * @param mesh defines the mesh that will use this material
  35152. * @param options defines additional options for compiling the shaders
  35153. * @returns a promise that resolves when the compilation completes
  35154. */
  35155. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35156. var _this = this;
  35157. return new Promise(function (resolve) {
  35158. _this.forceCompilation(mesh, function () {
  35159. resolve();
  35160. }, options);
  35161. });
  35162. };
  35163. /**
  35164. * Marks a define in the material to indicate that it needs to be re-computed
  35165. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35166. */
  35167. Material.prototype.markAsDirty = function (flag) {
  35168. if (flag & Material.TextureDirtyFlag) {
  35169. this._markAllSubMeshesAsTexturesDirty();
  35170. }
  35171. if (flag & Material.LightDirtyFlag) {
  35172. this._markAllSubMeshesAsLightsDirty();
  35173. }
  35174. if (flag & Material.FresnelDirtyFlag) {
  35175. this._markAllSubMeshesAsFresnelDirty();
  35176. }
  35177. if (flag & Material.AttributesDirtyFlag) {
  35178. this._markAllSubMeshesAsAttributesDirty();
  35179. }
  35180. if (flag & Material.MiscDirtyFlag) {
  35181. this._markAllSubMeshesAsMiscDirty();
  35182. }
  35183. this.getScene().resetCachedMaterial();
  35184. };
  35185. /**
  35186. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35187. * @param func defines a function which checks material defines against the submeshes
  35188. */
  35189. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35190. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35191. var mesh = _a[_i];
  35192. if (!mesh.subMeshes) {
  35193. continue;
  35194. }
  35195. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35196. var subMesh = _c[_b];
  35197. if (subMesh.getMaterial() !== this) {
  35198. continue;
  35199. }
  35200. if (!subMesh._materialDefines) {
  35201. continue;
  35202. }
  35203. func(subMesh._materialDefines);
  35204. }
  35205. }
  35206. };
  35207. /**
  35208. * Indicates that image processing needs to be re-calculated for all submeshes
  35209. */
  35210. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35211. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35212. };
  35213. /**
  35214. * Indicates that textures need to be re-calculated for all submeshes
  35215. */
  35216. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35217. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35218. };
  35219. /**
  35220. * Indicates that fresnel needs to be re-calculated for all submeshes
  35221. */
  35222. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35223. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35224. };
  35225. /**
  35226. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35227. */
  35228. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35229. this._markAllSubMeshesAsDirty(function (defines) {
  35230. defines.markAsFresnelDirty();
  35231. defines.markAsMiscDirty();
  35232. });
  35233. };
  35234. /**
  35235. * Indicates that lights need to be re-calculated for all submeshes
  35236. */
  35237. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35238. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35239. };
  35240. /**
  35241. * Indicates that attributes need to be re-calculated for all submeshes
  35242. */
  35243. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35244. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35245. };
  35246. /**
  35247. * Indicates that misc needs to be re-calculated for all submeshes
  35248. */
  35249. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35250. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35251. };
  35252. /**
  35253. * Indicates that textures and misc need to be re-calculated for all submeshes
  35254. */
  35255. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35256. this._markAllSubMeshesAsDirty(function (defines) {
  35257. defines.markAsTexturesDirty();
  35258. defines.markAsMiscDirty();
  35259. });
  35260. };
  35261. /**
  35262. * Disposes the material
  35263. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35264. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35265. */
  35266. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35267. // Animations
  35268. this.getScene().stopAnimation(this);
  35269. this.getScene().freeProcessedMaterials();
  35270. // Remove from scene
  35271. var index = this._scene.materials.indexOf(this);
  35272. if (index >= 0) {
  35273. this._scene.materials.splice(index, 1);
  35274. }
  35275. // Remove from meshes
  35276. for (index = 0; index < this._scene.meshes.length; index++) {
  35277. var mesh = this._scene.meshes[index];
  35278. if (mesh.material === this) {
  35279. mesh.material = null;
  35280. if (mesh.geometry) {
  35281. var geometry = (mesh.geometry);
  35282. if (this.storeEffectOnSubMeshes) {
  35283. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35284. var subMesh = _a[_i];
  35285. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35286. if (forceDisposeEffect && subMesh._materialEffect) {
  35287. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35288. }
  35289. }
  35290. }
  35291. else {
  35292. geometry._releaseVertexArrayObject(this._effect);
  35293. }
  35294. }
  35295. }
  35296. }
  35297. this._uniformBuffer.dispose();
  35298. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35299. if (forceDisposeEffect && this._effect) {
  35300. if (!this.storeEffectOnSubMeshes) {
  35301. this._scene.getEngine()._releaseEffect(this._effect);
  35302. }
  35303. this._effect = null;
  35304. }
  35305. // Callback
  35306. this.onDisposeObservable.notifyObservers(this);
  35307. this.onDisposeObservable.clear();
  35308. this.onBindObservable.clear();
  35309. this.onUnBindObservable.clear();
  35310. };
  35311. /**
  35312. * Serializes this material
  35313. * @returns the serialized material object
  35314. */
  35315. Material.prototype.serialize = function () {
  35316. return BABYLON.SerializationHelper.Serialize(this);
  35317. };
  35318. /**
  35319. * Creates a MultiMaterial from parsed MultiMaterial data.
  35320. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35321. * @param scene defines the hosting scene
  35322. * @returns a new MultiMaterial
  35323. */
  35324. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35325. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35326. multiMaterial.id = parsedMultiMaterial.id;
  35327. if (BABYLON.Tags) {
  35328. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35329. }
  35330. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35331. var subMatId = parsedMultiMaterial.materials[matIndex];
  35332. if (subMatId) {
  35333. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35334. }
  35335. else {
  35336. multiMaterial.subMaterials.push(null);
  35337. }
  35338. }
  35339. return multiMaterial;
  35340. };
  35341. /**
  35342. * Creates a material from parsed material data
  35343. * @param parsedMaterial defines parsed material data
  35344. * @param scene defines the hosting scene
  35345. * @param rootUrl defines the root URL to use to load textures
  35346. * @returns a new material
  35347. */
  35348. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35349. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35350. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35351. }
  35352. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35353. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35354. if (!BABYLON.LegacyPBRMaterial) {
  35355. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35356. return;
  35357. }
  35358. }
  35359. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35360. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35361. ;
  35362. };
  35363. // Triangle views
  35364. Material._TriangleFillMode = 0;
  35365. Material._WireFrameFillMode = 1;
  35366. Material._PointFillMode = 2;
  35367. // Draw modes
  35368. Material._PointListDrawMode = 3;
  35369. Material._LineListDrawMode = 4;
  35370. Material._LineLoopDrawMode = 5;
  35371. Material._LineStripDrawMode = 6;
  35372. Material._TriangleStripDrawMode = 7;
  35373. Material._TriangleFanDrawMode = 8;
  35374. /**
  35375. * Stores the clock-wise side orientation
  35376. */
  35377. Material._ClockWiseSideOrientation = 0;
  35378. /**
  35379. * Stores the counter clock-wise side orientation
  35380. */
  35381. Material._CounterClockWiseSideOrientation = 1;
  35382. /**
  35383. * The dirty texture flag value
  35384. */
  35385. Material._TextureDirtyFlag = 1;
  35386. /**
  35387. * The dirty light flag value
  35388. */
  35389. Material._LightDirtyFlag = 2;
  35390. /**
  35391. * The dirty fresnel flag value
  35392. */
  35393. Material._FresnelDirtyFlag = 4;
  35394. /**
  35395. * The dirty attribute flag value
  35396. */
  35397. Material._AttributesDirtyFlag = 8;
  35398. /**
  35399. * The dirty misc flag value
  35400. */
  35401. Material._MiscDirtyFlag = 16;
  35402. __decorate([
  35403. BABYLON.serialize()
  35404. ], Material.prototype, "id", void 0);
  35405. __decorate([
  35406. BABYLON.serialize()
  35407. ], Material.prototype, "name", void 0);
  35408. __decorate([
  35409. BABYLON.serialize()
  35410. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35411. __decorate([
  35412. BABYLON.serialize()
  35413. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35414. __decorate([
  35415. BABYLON.serialize()
  35416. ], Material.prototype, "state", void 0);
  35417. __decorate([
  35418. BABYLON.serialize("alpha")
  35419. ], Material.prototype, "_alpha", void 0);
  35420. __decorate([
  35421. BABYLON.serialize("backFaceCulling")
  35422. ], Material.prototype, "_backFaceCulling", void 0);
  35423. __decorate([
  35424. BABYLON.serialize()
  35425. ], Material.prototype, "sideOrientation", void 0);
  35426. __decorate([
  35427. BABYLON.serialize("alphaMode")
  35428. ], Material.prototype, "_alphaMode", void 0);
  35429. __decorate([
  35430. BABYLON.serialize()
  35431. ], Material.prototype, "_needDepthPrePass", void 0);
  35432. __decorate([
  35433. BABYLON.serialize()
  35434. ], Material.prototype, "disableDepthWrite", void 0);
  35435. __decorate([
  35436. BABYLON.serialize()
  35437. ], Material.prototype, "forceDepthWrite", void 0);
  35438. __decorate([
  35439. BABYLON.serialize()
  35440. ], Material.prototype, "separateCullingPass", void 0);
  35441. __decorate([
  35442. BABYLON.serialize("fogEnabled")
  35443. ], Material.prototype, "_fogEnabled", void 0);
  35444. __decorate([
  35445. BABYLON.serialize()
  35446. ], Material.prototype, "pointSize", void 0);
  35447. __decorate([
  35448. BABYLON.serialize()
  35449. ], Material.prototype, "zOffset", void 0);
  35450. __decorate([
  35451. BABYLON.serialize()
  35452. ], Material.prototype, "wireframe", null);
  35453. __decorate([
  35454. BABYLON.serialize()
  35455. ], Material.prototype, "pointsCloud", null);
  35456. __decorate([
  35457. BABYLON.serialize()
  35458. ], Material.prototype, "fillMode", null);
  35459. return Material;
  35460. }());
  35461. BABYLON.Material = Material;
  35462. })(BABYLON || (BABYLON = {}));
  35463. //# sourceMappingURL=babylon.material.js.map
  35464. var BABYLON;
  35465. (function (BABYLON) {
  35466. var UniformBuffer = /** @class */ (function () {
  35467. /**
  35468. * Uniform buffer objects.
  35469. *
  35470. * Handles blocks of uniform on the GPU.
  35471. *
  35472. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35473. *
  35474. * For more information, please refer to :
  35475. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35476. */
  35477. function UniformBuffer(engine, data, dynamic) {
  35478. this._engine = engine;
  35479. this._noUBO = !engine.supportsUniformBuffers;
  35480. this._dynamic = dynamic;
  35481. this._data = data || [];
  35482. this._uniformLocations = {};
  35483. this._uniformSizes = {};
  35484. this._uniformLocationPointer = 0;
  35485. this._needSync = false;
  35486. if (this._noUBO) {
  35487. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35488. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35489. this.updateFloat = this._updateFloatForEffect;
  35490. this.updateFloat2 = this._updateFloat2ForEffect;
  35491. this.updateFloat3 = this._updateFloat3ForEffect;
  35492. this.updateFloat4 = this._updateFloat4ForEffect;
  35493. this.updateMatrix = this._updateMatrixForEffect;
  35494. this.updateVector3 = this._updateVector3ForEffect;
  35495. this.updateVector4 = this._updateVector4ForEffect;
  35496. this.updateColor3 = this._updateColor3ForEffect;
  35497. this.updateColor4 = this._updateColor4ForEffect;
  35498. }
  35499. else {
  35500. this._engine._uniformBuffers.push(this);
  35501. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35502. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35503. this.updateFloat = this._updateFloatForUniform;
  35504. this.updateFloat2 = this._updateFloat2ForUniform;
  35505. this.updateFloat3 = this._updateFloat3ForUniform;
  35506. this.updateFloat4 = this._updateFloat4ForUniform;
  35507. this.updateMatrix = this._updateMatrixForUniform;
  35508. this.updateVector3 = this._updateVector3ForUniform;
  35509. this.updateVector4 = this._updateVector4ForUniform;
  35510. this.updateColor3 = this._updateColor3ForUniform;
  35511. this.updateColor4 = this._updateColor4ForUniform;
  35512. }
  35513. }
  35514. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35515. // Properties
  35516. /**
  35517. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35518. * or just falling back on setUniformXXX calls.
  35519. */
  35520. get: function () {
  35521. return !this._noUBO;
  35522. },
  35523. enumerable: true,
  35524. configurable: true
  35525. });
  35526. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35527. /**
  35528. * Indicates if the WebGL underlying uniform buffer is in sync
  35529. * with the javascript cache data.
  35530. */
  35531. get: function () {
  35532. return !this._needSync;
  35533. },
  35534. enumerable: true,
  35535. configurable: true
  35536. });
  35537. /**
  35538. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35539. * Also, a dynamic UniformBuffer will disable cache verification and always
  35540. * update the underlying WebGL uniform buffer to the GPU.
  35541. */
  35542. UniformBuffer.prototype.isDynamic = function () {
  35543. return this._dynamic !== undefined;
  35544. };
  35545. /**
  35546. * The data cache on JS side.
  35547. */
  35548. UniformBuffer.prototype.getData = function () {
  35549. return this._bufferData;
  35550. };
  35551. /**
  35552. * The underlying WebGL Uniform buffer.
  35553. */
  35554. UniformBuffer.prototype.getBuffer = function () {
  35555. return this._buffer;
  35556. };
  35557. /**
  35558. * std140 layout specifies how to align data within an UBO structure.
  35559. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35560. * for specs.
  35561. */
  35562. UniformBuffer.prototype._fillAlignment = function (size) {
  35563. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35564. // and 4x4 matrices
  35565. // TODO : change if other types are used
  35566. var alignment;
  35567. if (size <= 2) {
  35568. alignment = size;
  35569. }
  35570. else {
  35571. alignment = 4;
  35572. }
  35573. if ((this._uniformLocationPointer % alignment) !== 0) {
  35574. var oldPointer = this._uniformLocationPointer;
  35575. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35576. var diff = this._uniformLocationPointer - oldPointer;
  35577. for (var i = 0; i < diff; i++) {
  35578. this._data.push(0);
  35579. }
  35580. }
  35581. };
  35582. /**
  35583. * Adds an uniform in the buffer.
  35584. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35585. * for the layout to be correct !
  35586. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35587. * @param {number|number[]} size Data size, or data directly.
  35588. */
  35589. UniformBuffer.prototype.addUniform = function (name, size) {
  35590. if (this._noUBO) {
  35591. return;
  35592. }
  35593. if (this._uniformLocations[name] !== undefined) {
  35594. // Already existing uniform
  35595. return;
  35596. }
  35597. // This function must be called in the order of the shader layout !
  35598. // size can be the size of the uniform, or data directly
  35599. var data;
  35600. if (size instanceof Array) {
  35601. data = size;
  35602. size = data.length;
  35603. }
  35604. else {
  35605. size = size;
  35606. data = [];
  35607. // Fill with zeros
  35608. for (var i = 0; i < size; i++) {
  35609. data.push(0);
  35610. }
  35611. }
  35612. this._fillAlignment(size);
  35613. this._uniformSizes[name] = size;
  35614. this._uniformLocations[name] = this._uniformLocationPointer;
  35615. this._uniformLocationPointer += size;
  35616. for (var i = 0; i < size; i++) {
  35617. this._data.push(data[i]);
  35618. }
  35619. this._needSync = true;
  35620. };
  35621. /**
  35622. * Wrapper for addUniform.
  35623. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35624. * @param {Matrix} mat A 4x4 matrix.
  35625. */
  35626. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35627. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35628. };
  35629. /**
  35630. * Wrapper for addUniform.
  35631. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35632. * @param {number} x
  35633. * @param {number} y
  35634. */
  35635. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35636. var temp = [x, y];
  35637. this.addUniform(name, temp);
  35638. };
  35639. /**
  35640. * Wrapper for addUniform.
  35641. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35642. * @param {number} x
  35643. * @param {number} y
  35644. * @param {number} z
  35645. */
  35646. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35647. var temp = [x, y, z];
  35648. this.addUniform(name, temp);
  35649. };
  35650. /**
  35651. * Wrapper for addUniform.
  35652. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35653. * @param {Color3} color
  35654. */
  35655. UniformBuffer.prototype.addColor3 = function (name, color) {
  35656. var temp = new Array();
  35657. color.toArray(temp);
  35658. this.addUniform(name, temp);
  35659. };
  35660. /**
  35661. * Wrapper for addUniform.
  35662. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35663. * @param {Color3} color
  35664. * @param {number} alpha
  35665. */
  35666. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35667. var temp = new Array();
  35668. color.toArray(temp);
  35669. temp.push(alpha);
  35670. this.addUniform(name, temp);
  35671. };
  35672. /**
  35673. * Wrapper for addUniform.
  35674. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35675. * @param {Vector3} vector
  35676. */
  35677. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35678. var temp = new Array();
  35679. vector.toArray(temp);
  35680. this.addUniform(name, temp);
  35681. };
  35682. /**
  35683. * Wrapper for addUniform.
  35684. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35685. */
  35686. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35687. this.addUniform(name, 12);
  35688. };
  35689. /**
  35690. * Wrapper for addUniform.
  35691. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35692. */
  35693. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35694. this.addUniform(name, 8);
  35695. };
  35696. /**
  35697. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35698. */
  35699. UniformBuffer.prototype.create = function () {
  35700. if (this._noUBO) {
  35701. return;
  35702. }
  35703. if (this._buffer) {
  35704. return; // nothing to do
  35705. }
  35706. // See spec, alignment must be filled as a vec4
  35707. this._fillAlignment(4);
  35708. this._bufferData = new Float32Array(this._data);
  35709. this._rebuild();
  35710. this._needSync = true;
  35711. };
  35712. UniformBuffer.prototype._rebuild = function () {
  35713. if (this._noUBO) {
  35714. return;
  35715. }
  35716. if (this._dynamic) {
  35717. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35718. }
  35719. else {
  35720. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35721. }
  35722. };
  35723. /**
  35724. * Updates the WebGL Uniform Buffer on the GPU.
  35725. * If the `dynamic` flag is set to true, no cache comparison is done.
  35726. * Otherwise, the buffer will be updated only if the cache differs.
  35727. */
  35728. UniformBuffer.prototype.update = function () {
  35729. if (!this._buffer) {
  35730. this.create();
  35731. return;
  35732. }
  35733. if (!this._dynamic && !this._needSync) {
  35734. return;
  35735. }
  35736. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35737. this._needSync = false;
  35738. };
  35739. /**
  35740. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35741. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35742. * @param {number[]|Float32Array} data Flattened data
  35743. * @param {number} size Size of the data.
  35744. */
  35745. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35746. var location = this._uniformLocations[uniformName];
  35747. if (location === undefined) {
  35748. if (this._buffer) {
  35749. // Cannot add an uniform if the buffer is already created
  35750. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35751. return;
  35752. }
  35753. this.addUniform(uniformName, size);
  35754. location = this._uniformLocations[uniformName];
  35755. }
  35756. if (!this._buffer) {
  35757. this.create();
  35758. }
  35759. if (!this._dynamic) {
  35760. // Cache for static uniform buffers
  35761. var changed = false;
  35762. for (var i = 0; i < size; i++) {
  35763. if (this._bufferData[location + i] !== data[i]) {
  35764. changed = true;
  35765. this._bufferData[location + i] = data[i];
  35766. }
  35767. }
  35768. this._needSync = this._needSync || changed;
  35769. }
  35770. else {
  35771. // No cache for dynamic
  35772. for (var i = 0; i < size; i++) {
  35773. this._bufferData[location + i] = data[i];
  35774. }
  35775. }
  35776. };
  35777. // Update methods
  35778. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35779. // To match std140, matrix must be realigned
  35780. for (var i = 0; i < 3; i++) {
  35781. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35782. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35783. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35784. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35785. }
  35786. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35787. };
  35788. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35789. this._currentEffect.setMatrix3x3(name, matrix);
  35790. };
  35791. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35792. this._currentEffect.setMatrix2x2(name, matrix);
  35793. };
  35794. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35795. // To match std140, matrix must be realigned
  35796. for (var i = 0; i < 2; i++) {
  35797. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35798. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35799. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35800. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35801. }
  35802. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35803. };
  35804. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35805. this._currentEffect.setFloat(name, x);
  35806. };
  35807. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35808. UniformBuffer._tempBuffer[0] = x;
  35809. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35810. };
  35811. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35812. if (suffix === void 0) { suffix = ""; }
  35813. this._currentEffect.setFloat2(name + suffix, x, y);
  35814. };
  35815. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35816. if (suffix === void 0) { suffix = ""; }
  35817. UniformBuffer._tempBuffer[0] = x;
  35818. UniformBuffer._tempBuffer[1] = y;
  35819. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35820. };
  35821. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35822. if (suffix === void 0) { suffix = ""; }
  35823. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35824. };
  35825. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35826. if (suffix === void 0) { suffix = ""; }
  35827. UniformBuffer._tempBuffer[0] = x;
  35828. UniformBuffer._tempBuffer[1] = y;
  35829. UniformBuffer._tempBuffer[2] = z;
  35830. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35831. };
  35832. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35833. if (suffix === void 0) { suffix = ""; }
  35834. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35835. };
  35836. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35837. if (suffix === void 0) { suffix = ""; }
  35838. UniformBuffer._tempBuffer[0] = x;
  35839. UniformBuffer._tempBuffer[1] = y;
  35840. UniformBuffer._tempBuffer[2] = z;
  35841. UniformBuffer._tempBuffer[3] = w;
  35842. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35843. };
  35844. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35845. this._currentEffect.setMatrix(name, mat);
  35846. };
  35847. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35848. this.updateUniform(name, mat.toArray(), 16);
  35849. };
  35850. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35851. this._currentEffect.setVector3(name, vector);
  35852. };
  35853. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35854. vector.toArray(UniformBuffer._tempBuffer);
  35855. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35856. };
  35857. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35858. this._currentEffect.setVector4(name, vector);
  35859. };
  35860. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35861. vector.toArray(UniformBuffer._tempBuffer);
  35862. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35863. };
  35864. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35865. if (suffix === void 0) { suffix = ""; }
  35866. this._currentEffect.setColor3(name + suffix, color);
  35867. };
  35868. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35869. if (suffix === void 0) { suffix = ""; }
  35870. color.toArray(UniformBuffer._tempBuffer);
  35871. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35872. };
  35873. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35874. if (suffix === void 0) { suffix = ""; }
  35875. this._currentEffect.setColor4(name + suffix, color, alpha);
  35876. };
  35877. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35878. if (suffix === void 0) { suffix = ""; }
  35879. color.toArray(UniformBuffer._tempBuffer);
  35880. UniformBuffer._tempBuffer[3] = alpha;
  35881. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35882. };
  35883. /**
  35884. * Sets a sampler uniform on the effect.
  35885. * @param {string} name Name of the sampler.
  35886. * @param {Texture} texture
  35887. */
  35888. UniformBuffer.prototype.setTexture = function (name, texture) {
  35889. this._currentEffect.setTexture(name, texture);
  35890. };
  35891. /**
  35892. * Directly updates the value of the uniform in the cache AND on the GPU.
  35893. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35894. * @param {number[]|Float32Array} data Flattened data
  35895. */
  35896. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35897. this.updateUniform(uniformName, data, data.length);
  35898. this.update();
  35899. };
  35900. /**
  35901. * Binds this uniform buffer to an effect.
  35902. * @param {Effect} effect
  35903. * @param {string} name Name of the uniform block in the shader.
  35904. */
  35905. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35906. this._currentEffect = effect;
  35907. if (this._noUBO || !this._buffer) {
  35908. return;
  35909. }
  35910. effect.bindUniformBuffer(this._buffer, name);
  35911. };
  35912. /**
  35913. * Disposes the uniform buffer.
  35914. */
  35915. UniformBuffer.prototype.dispose = function () {
  35916. if (this._noUBO) {
  35917. return;
  35918. }
  35919. var index = this._engine._uniformBuffers.indexOf(this);
  35920. if (index !== -1) {
  35921. this._engine._uniformBuffers.splice(index, 1);
  35922. }
  35923. if (!this._buffer) {
  35924. return;
  35925. }
  35926. if (this._engine._releaseBuffer(this._buffer)) {
  35927. this._buffer = null;
  35928. }
  35929. };
  35930. // Pool for avoiding memory leaks
  35931. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35932. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35933. return UniformBuffer;
  35934. }());
  35935. BABYLON.UniformBuffer = UniformBuffer;
  35936. })(BABYLON || (BABYLON = {}));
  35937. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35938. var BABYLON;
  35939. (function (BABYLON) {
  35940. /**
  35941. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35942. */
  35943. var VertexData = /** @class */ (function () {
  35944. function VertexData() {
  35945. }
  35946. /**
  35947. * Uses the passed data array to set the set the values for the specified kind of data
  35948. * @param data a linear array of floating numbers
  35949. * @param kind the type of data that is being set, eg positions, colors etc
  35950. */
  35951. VertexData.prototype.set = function (data, kind) {
  35952. switch (kind) {
  35953. case BABYLON.VertexBuffer.PositionKind:
  35954. this.positions = data;
  35955. break;
  35956. case BABYLON.VertexBuffer.NormalKind:
  35957. this.normals = data;
  35958. break;
  35959. case BABYLON.VertexBuffer.TangentKind:
  35960. this.tangents = data;
  35961. break;
  35962. case BABYLON.VertexBuffer.UVKind:
  35963. this.uvs = data;
  35964. break;
  35965. case BABYLON.VertexBuffer.UV2Kind:
  35966. this.uvs2 = data;
  35967. break;
  35968. case BABYLON.VertexBuffer.UV3Kind:
  35969. this.uvs3 = data;
  35970. break;
  35971. case BABYLON.VertexBuffer.UV4Kind:
  35972. this.uvs4 = data;
  35973. break;
  35974. case BABYLON.VertexBuffer.UV5Kind:
  35975. this.uvs5 = data;
  35976. break;
  35977. case BABYLON.VertexBuffer.UV6Kind:
  35978. this.uvs6 = data;
  35979. break;
  35980. case BABYLON.VertexBuffer.ColorKind:
  35981. this.colors = data;
  35982. break;
  35983. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35984. this.matricesIndices = data;
  35985. break;
  35986. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35987. this.matricesWeights = data;
  35988. break;
  35989. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35990. this.matricesIndicesExtra = data;
  35991. break;
  35992. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35993. this.matricesWeightsExtra = data;
  35994. break;
  35995. }
  35996. };
  35997. /**
  35998. * Associates the vertexData to the passed Mesh.
  35999. * Sets it as updatable or not (default `false`)
  36000. * @param mesh the mesh the vertexData is applied to
  36001. * @param updatable when used and having the value true allows new data to update the vertexData
  36002. * @returns the VertexData
  36003. */
  36004. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36005. this._applyTo(mesh, updatable);
  36006. return this;
  36007. };
  36008. /**
  36009. * Associates the vertexData to the passed Geometry.
  36010. * Sets it as updatable or not (default `false`)
  36011. * @param geometry the geometry the vertexData is applied to
  36012. * @param updatable when used and having the value true allows new data to update the vertexData
  36013. * @returns VertexData
  36014. */
  36015. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36016. this._applyTo(geometry, updatable);
  36017. return this;
  36018. };
  36019. /**
  36020. * Updates the associated mesh
  36021. * @param mesh the mesh to be updated
  36022. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36023. * @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
  36024. * @returns VertexData
  36025. */
  36026. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36027. this._update(mesh);
  36028. return this;
  36029. };
  36030. /**
  36031. * Updates the associated geometry
  36032. * @param geometry the geometry to be updated
  36033. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36034. * @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
  36035. * @returns VertexData.
  36036. */
  36037. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36038. this._update(geometry);
  36039. return this;
  36040. };
  36041. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36042. if (updatable === void 0) { updatable = false; }
  36043. if (this.positions) {
  36044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36045. }
  36046. if (this.normals) {
  36047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36048. }
  36049. if (this.tangents) {
  36050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36051. }
  36052. if (this.uvs) {
  36053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36054. }
  36055. if (this.uvs2) {
  36056. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36057. }
  36058. if (this.uvs3) {
  36059. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36060. }
  36061. if (this.uvs4) {
  36062. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36063. }
  36064. if (this.uvs5) {
  36065. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36066. }
  36067. if (this.uvs6) {
  36068. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36069. }
  36070. if (this.colors) {
  36071. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36072. }
  36073. if (this.matricesIndices) {
  36074. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36075. }
  36076. if (this.matricesWeights) {
  36077. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36078. }
  36079. if (this.matricesIndicesExtra) {
  36080. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36081. }
  36082. if (this.matricesWeightsExtra) {
  36083. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36084. }
  36085. if (this.indices) {
  36086. meshOrGeometry.setIndices(this.indices, null, updatable);
  36087. }
  36088. return this;
  36089. };
  36090. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36091. if (this.positions) {
  36092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36093. }
  36094. if (this.normals) {
  36095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36096. }
  36097. if (this.tangents) {
  36098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36099. }
  36100. if (this.uvs) {
  36101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36102. }
  36103. if (this.uvs2) {
  36104. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36105. }
  36106. if (this.uvs3) {
  36107. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36108. }
  36109. if (this.uvs4) {
  36110. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36111. }
  36112. if (this.uvs5) {
  36113. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36114. }
  36115. if (this.uvs6) {
  36116. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36117. }
  36118. if (this.colors) {
  36119. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36120. }
  36121. if (this.matricesIndices) {
  36122. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36123. }
  36124. if (this.matricesWeights) {
  36125. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36126. }
  36127. if (this.matricesIndicesExtra) {
  36128. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36129. }
  36130. if (this.matricesWeightsExtra) {
  36131. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36132. }
  36133. if (this.indices) {
  36134. meshOrGeometry.setIndices(this.indices, null);
  36135. }
  36136. return this;
  36137. };
  36138. /**
  36139. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36140. * @param matrix the transforming matrix
  36141. * @returns the VertexData
  36142. */
  36143. VertexData.prototype.transform = function (matrix) {
  36144. var transformed = BABYLON.Vector3.Zero();
  36145. var index;
  36146. if (this.positions) {
  36147. var position = BABYLON.Vector3.Zero();
  36148. for (index = 0; index < this.positions.length; index += 3) {
  36149. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36150. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36151. this.positions[index] = transformed.x;
  36152. this.positions[index + 1] = transformed.y;
  36153. this.positions[index + 2] = transformed.z;
  36154. }
  36155. }
  36156. if (this.normals) {
  36157. var normal = BABYLON.Vector3.Zero();
  36158. for (index = 0; index < this.normals.length; index += 3) {
  36159. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36160. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36161. this.normals[index] = transformed.x;
  36162. this.normals[index + 1] = transformed.y;
  36163. this.normals[index + 2] = transformed.z;
  36164. }
  36165. }
  36166. if (this.tangents) {
  36167. var tangent = BABYLON.Vector4.Zero();
  36168. var tangentTransformed = BABYLON.Vector4.Zero();
  36169. for (index = 0; index < this.tangents.length; index += 4) {
  36170. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36171. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36172. this.tangents[index] = tangentTransformed.x;
  36173. this.tangents[index + 1] = tangentTransformed.y;
  36174. this.tangents[index + 2] = tangentTransformed.z;
  36175. this.tangents[index + 3] = tangentTransformed.w;
  36176. }
  36177. }
  36178. return this;
  36179. };
  36180. /**
  36181. * Merges the passed VertexData into the current one
  36182. * @param other the VertexData to be merged into the current one
  36183. * @returns the modified VertexData
  36184. */
  36185. VertexData.prototype.merge = function (other) {
  36186. this._validate();
  36187. other._validate();
  36188. if (!this.normals !== !other.normals ||
  36189. !this.tangents !== !other.tangents ||
  36190. !this.uvs !== !other.uvs ||
  36191. !this.uvs2 !== !other.uvs2 ||
  36192. !this.uvs3 !== !other.uvs3 ||
  36193. !this.uvs4 !== !other.uvs4 ||
  36194. !this.uvs5 !== !other.uvs5 ||
  36195. !this.uvs6 !== !other.uvs6 ||
  36196. !this.colors !== !other.colors ||
  36197. !this.matricesIndices !== !other.matricesIndices ||
  36198. !this.matricesWeights !== !other.matricesWeights ||
  36199. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36200. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36201. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36202. }
  36203. if (other.indices) {
  36204. if (!this.indices) {
  36205. this.indices = [];
  36206. }
  36207. var offset = this.positions ? this.positions.length / 3 : 0;
  36208. for (var index = 0; index < other.indices.length; index++) {
  36209. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36210. this.indices.push(other.indices[index] + offset);
  36211. }
  36212. }
  36213. this.positions = this._mergeElement(this.positions, other.positions);
  36214. this.normals = this._mergeElement(this.normals, other.normals);
  36215. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36216. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36217. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36218. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36219. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36220. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36221. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36222. this.colors = this._mergeElement(this.colors, other.colors);
  36223. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36224. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36225. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36226. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36227. return this;
  36228. };
  36229. VertexData.prototype._mergeElement = function (source, other) {
  36230. if (!source) {
  36231. return other;
  36232. }
  36233. if (!other) {
  36234. return source;
  36235. }
  36236. var len = other.length + source.length;
  36237. var isSrcTypedArray = source instanceof Float32Array;
  36238. var isOthTypedArray = other instanceof Float32Array;
  36239. // use non-loop method when the source is Float32Array
  36240. if (isSrcTypedArray) {
  36241. var ret32 = new Float32Array(len);
  36242. ret32.set(source);
  36243. ret32.set(other, source.length);
  36244. return ret32;
  36245. // source is number[], when other is also use concat
  36246. }
  36247. else if (!isOthTypedArray) {
  36248. return source.concat(other);
  36249. // source is a number[], but other is a Float32Array, loop required
  36250. }
  36251. else {
  36252. var ret = source.slice(0); // copy source to a separate array
  36253. for (var i = 0, len = other.length; i < len; i++) {
  36254. ret.push(other[i]);
  36255. }
  36256. return ret;
  36257. }
  36258. };
  36259. VertexData.prototype._validate = function () {
  36260. if (!this.positions) {
  36261. throw new Error("Positions are required");
  36262. }
  36263. var getElementCount = function (kind, values) {
  36264. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36265. if ((values.length % stride) !== 0) {
  36266. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36267. }
  36268. return values.length / stride;
  36269. };
  36270. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36271. var validateElementCount = function (kind, values) {
  36272. var elementCount = getElementCount(kind, values);
  36273. if (elementCount !== positionsElementCount) {
  36274. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36275. }
  36276. };
  36277. if (this.normals)
  36278. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36279. if (this.tangents)
  36280. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36281. if (this.uvs)
  36282. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36283. if (this.uvs2)
  36284. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36285. if (this.uvs3)
  36286. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36287. if (this.uvs4)
  36288. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36289. if (this.uvs5)
  36290. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36291. if (this.uvs6)
  36292. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36293. if (this.colors)
  36294. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36295. if (this.matricesIndices)
  36296. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36297. if (this.matricesWeights)
  36298. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36299. if (this.matricesIndicesExtra)
  36300. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36301. if (this.matricesWeightsExtra)
  36302. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36303. };
  36304. /**
  36305. * Serializes the VertexData
  36306. * @returns a serialized object
  36307. */
  36308. VertexData.prototype.serialize = function () {
  36309. var serializationObject = this.serialize();
  36310. if (this.positions) {
  36311. serializationObject.positions = this.positions;
  36312. }
  36313. if (this.normals) {
  36314. serializationObject.normals = this.normals;
  36315. }
  36316. if (this.tangents) {
  36317. serializationObject.tangents = this.tangents;
  36318. }
  36319. if (this.uvs) {
  36320. serializationObject.uvs = this.uvs;
  36321. }
  36322. if (this.uvs2) {
  36323. serializationObject.uvs2 = this.uvs2;
  36324. }
  36325. if (this.uvs3) {
  36326. serializationObject.uvs3 = this.uvs3;
  36327. }
  36328. if (this.uvs4) {
  36329. serializationObject.uvs4 = this.uvs4;
  36330. }
  36331. if (this.uvs5) {
  36332. serializationObject.uvs5 = this.uvs5;
  36333. }
  36334. if (this.uvs6) {
  36335. serializationObject.uvs6 = this.uvs6;
  36336. }
  36337. if (this.colors) {
  36338. serializationObject.colors = this.colors;
  36339. }
  36340. if (this.matricesIndices) {
  36341. serializationObject.matricesIndices = this.matricesIndices;
  36342. serializationObject.matricesIndices._isExpanded = true;
  36343. }
  36344. if (this.matricesWeights) {
  36345. serializationObject.matricesWeights = this.matricesWeights;
  36346. }
  36347. if (this.matricesIndicesExtra) {
  36348. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36349. serializationObject.matricesIndicesExtra._isExpanded = true;
  36350. }
  36351. if (this.matricesWeightsExtra) {
  36352. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36353. }
  36354. serializationObject.indices = this.indices;
  36355. return serializationObject;
  36356. };
  36357. // Statics
  36358. /**
  36359. * Extracts the vertexData from a mesh
  36360. * @param mesh the mesh from which to extract the VertexData
  36361. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36362. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36363. * @returns the object VertexData associated to the passed mesh
  36364. */
  36365. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36366. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36367. };
  36368. /**
  36369. * Extracts the vertexData from the geometry
  36370. * @param geometry the geometry from which to extract the VertexData
  36371. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36372. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36373. * @returns the object VertexData associated to the passed mesh
  36374. */
  36375. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36376. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36377. };
  36378. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36379. var result = new VertexData();
  36380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36381. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36382. }
  36383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36384. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36385. }
  36386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36387. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36388. }
  36389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36390. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36391. }
  36392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36393. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36394. }
  36395. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36396. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36397. }
  36398. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36399. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36400. }
  36401. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36402. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36403. }
  36404. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36405. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36406. }
  36407. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36408. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36409. }
  36410. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36411. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36412. }
  36413. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36414. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36415. }
  36416. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36417. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36418. }
  36419. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36420. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36421. }
  36422. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36423. return result;
  36424. };
  36425. /**
  36426. * Creates the VertexData for a Ribbon
  36427. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36428. * * pathArray array of paths, each of which an array of successive Vector3
  36429. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36430. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36431. * * 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
  36432. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36433. * * 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)
  36434. * * 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)
  36435. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36436. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36437. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36438. * @returns the VertexData of the ribbon
  36439. */
  36440. VertexData.CreateRibbon = function (options) {
  36441. var pathArray = options.pathArray;
  36442. var closeArray = options.closeArray || false;
  36443. var closePath = options.closePath || false;
  36444. var invertUV = options.invertUV || false;
  36445. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36446. var offset = options.offset || defaultOffset;
  36447. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36448. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36449. var customUV = options.uvs;
  36450. var customColors = options.colors;
  36451. var positions = [];
  36452. var indices = [];
  36453. var normals = [];
  36454. var uvs = [];
  36455. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36456. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36457. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36458. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36459. var minlg; // minimal length among all paths from pathArray
  36460. var lg = []; // array of path lengths : nb of vertex per path
  36461. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36462. var p; // path iterator
  36463. var i; // point iterator
  36464. var j; // point iterator
  36465. // if single path in pathArray
  36466. if (pathArray.length < 2) {
  36467. var ar1 = [];
  36468. var ar2 = [];
  36469. for (i = 0; i < pathArray[0].length - offset; i++) {
  36470. ar1.push(pathArray[0][i]);
  36471. ar2.push(pathArray[0][i + offset]);
  36472. }
  36473. pathArray = [ar1, ar2];
  36474. }
  36475. // positions and horizontal distances (u)
  36476. var idc = 0;
  36477. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36478. var path;
  36479. var l;
  36480. minlg = pathArray[0].length;
  36481. var vectlg;
  36482. var dist;
  36483. for (p = 0; p < pathArray.length; p++) {
  36484. uTotalDistance[p] = 0;
  36485. us[p] = [0];
  36486. path = pathArray[p];
  36487. l = path.length;
  36488. minlg = (minlg < l) ? minlg : l;
  36489. j = 0;
  36490. while (j < l) {
  36491. positions.push(path[j].x, path[j].y, path[j].z);
  36492. if (j > 0) {
  36493. vectlg = path[j].subtract(path[j - 1]).length();
  36494. dist = vectlg + uTotalDistance[p];
  36495. us[p].push(dist);
  36496. uTotalDistance[p] = dist;
  36497. }
  36498. j++;
  36499. }
  36500. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36501. j--;
  36502. positions.push(path[0].x, path[0].y, path[0].z);
  36503. vectlg = path[j].subtract(path[0]).length();
  36504. dist = vectlg + uTotalDistance[p];
  36505. us[p].push(dist);
  36506. uTotalDistance[p] = dist;
  36507. }
  36508. lg[p] = l + closePathCorr;
  36509. idx[p] = idc;
  36510. idc += (l + closePathCorr);
  36511. }
  36512. // vertical distances (v)
  36513. var path1;
  36514. var path2;
  36515. var vertex1 = null;
  36516. var vertex2 = null;
  36517. for (i = 0; i < minlg + closePathCorr; i++) {
  36518. vTotalDistance[i] = 0;
  36519. vs[i] = [0];
  36520. for (p = 0; p < pathArray.length - 1; p++) {
  36521. path1 = pathArray[p];
  36522. path2 = pathArray[p + 1];
  36523. if (i === minlg) { // closePath
  36524. vertex1 = path1[0];
  36525. vertex2 = path2[0];
  36526. }
  36527. else {
  36528. vertex1 = path1[i];
  36529. vertex2 = path2[i];
  36530. }
  36531. vectlg = vertex2.subtract(vertex1).length();
  36532. dist = vectlg + vTotalDistance[i];
  36533. vs[i].push(dist);
  36534. vTotalDistance[i] = dist;
  36535. }
  36536. if (closeArray && vertex2 && vertex1) {
  36537. path1 = pathArray[p];
  36538. path2 = pathArray[0];
  36539. if (i === minlg) { // closePath
  36540. vertex2 = path2[0];
  36541. }
  36542. vectlg = vertex2.subtract(vertex1).length();
  36543. dist = vectlg + vTotalDistance[i];
  36544. vTotalDistance[i] = dist;
  36545. }
  36546. }
  36547. // uvs
  36548. var u;
  36549. var v;
  36550. if (customUV) {
  36551. for (p = 0; p < customUV.length; p++) {
  36552. uvs.push(customUV[p].x, customUV[p].y);
  36553. }
  36554. }
  36555. else {
  36556. for (p = 0; p < pathArray.length; p++) {
  36557. for (i = 0; i < minlg + closePathCorr; i++) {
  36558. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36559. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36560. if (invertUV) {
  36561. uvs.push(v, u);
  36562. }
  36563. else {
  36564. uvs.push(u, v);
  36565. }
  36566. }
  36567. }
  36568. }
  36569. // indices
  36570. p = 0; // path index
  36571. var pi = 0; // positions array index
  36572. var l1 = lg[p] - 1; // path1 length
  36573. var l2 = lg[p + 1] - 1; // path2 length
  36574. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36575. var shft = idx[1] - idx[0]; // shift
  36576. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36577. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36578. // 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
  36579. indices.push(pi, pi + shft, pi + 1);
  36580. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36581. pi += 1;
  36582. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36583. p++;
  36584. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36585. shft = idx[0] - idx[p];
  36586. l1 = lg[p] - 1;
  36587. l2 = lg[0] - 1;
  36588. }
  36589. else {
  36590. shft = idx[p + 1] - idx[p];
  36591. l1 = lg[p] - 1;
  36592. l2 = lg[p + 1] - 1;
  36593. }
  36594. pi = idx[p];
  36595. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36596. }
  36597. }
  36598. // normals
  36599. VertexData.ComputeNormals(positions, indices, normals);
  36600. if (closePath) { // update both the first and last vertex normals to their average value
  36601. var indexFirst = 0;
  36602. var indexLast = 0;
  36603. for (p = 0; p < pathArray.length; p++) {
  36604. indexFirst = idx[p] * 3;
  36605. if (p + 1 < pathArray.length) {
  36606. indexLast = (idx[p + 1] - 1) * 3;
  36607. }
  36608. else {
  36609. indexLast = normals.length - 3;
  36610. }
  36611. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36612. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36613. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36614. normals[indexLast] = normals[indexFirst];
  36615. normals[indexLast + 1] = normals[indexFirst + 1];
  36616. normals[indexLast + 2] = normals[indexFirst + 2];
  36617. }
  36618. }
  36619. // sides
  36620. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36621. // Colors
  36622. var colors = null;
  36623. if (customColors) {
  36624. colors = new Float32Array(customColors.length * 4);
  36625. for (var c = 0; c < customColors.length; c++) {
  36626. colors[c * 4] = customColors[c].r;
  36627. colors[c * 4 + 1] = customColors[c].g;
  36628. colors[c * 4 + 2] = customColors[c].b;
  36629. colors[c * 4 + 3] = customColors[c].a;
  36630. }
  36631. }
  36632. // Result
  36633. var vertexData = new VertexData();
  36634. var positions32 = new Float32Array(positions);
  36635. var normals32 = new Float32Array(normals);
  36636. var uvs32 = new Float32Array(uvs);
  36637. vertexData.indices = indices;
  36638. vertexData.positions = positions32;
  36639. vertexData.normals = normals32;
  36640. vertexData.uvs = uvs32;
  36641. if (colors) {
  36642. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36643. }
  36644. if (closePath) {
  36645. vertexData._idx = idx;
  36646. }
  36647. return vertexData;
  36648. };
  36649. /**
  36650. * Creates the VertexData for a box
  36651. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36652. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36653. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36654. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36655. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36656. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36657. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36658. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36659. * * 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)
  36660. * * 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)
  36661. * @returns the VertexData of the box
  36662. */
  36663. VertexData.CreateBox = function (options) {
  36664. var normalsSource = [
  36665. new BABYLON.Vector3(0, 0, 1),
  36666. new BABYLON.Vector3(0, 0, -1),
  36667. new BABYLON.Vector3(1, 0, 0),
  36668. new BABYLON.Vector3(-1, 0, 0),
  36669. new BABYLON.Vector3(0, 1, 0),
  36670. new BABYLON.Vector3(0, -1, 0)
  36671. ];
  36672. var indices = [];
  36673. var positions = [];
  36674. var normals = [];
  36675. var uvs = [];
  36676. var width = options.width || options.size || 1;
  36677. var height = options.height || options.size || 1;
  36678. var depth = options.depth || options.size || 1;
  36679. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36680. var faceUV = options.faceUV || new Array(6);
  36681. var faceColors = options.faceColors;
  36682. var colors = [];
  36683. // default face colors and UV if undefined
  36684. for (var f = 0; f < 6; f++) {
  36685. if (faceUV[f] === undefined) {
  36686. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36687. }
  36688. if (faceColors && faceColors[f] === undefined) {
  36689. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36690. }
  36691. }
  36692. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36693. // Create each face in turn.
  36694. for (var index = 0; index < normalsSource.length; index++) {
  36695. var normal = normalsSource[index];
  36696. // Get two vectors perpendicular to the face normal and to each other.
  36697. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36698. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36699. // Six indices (two triangles) per face.
  36700. var verticesLength = positions.length / 3;
  36701. indices.push(verticesLength);
  36702. indices.push(verticesLength + 1);
  36703. indices.push(verticesLength + 2);
  36704. indices.push(verticesLength);
  36705. indices.push(verticesLength + 2);
  36706. indices.push(verticesLength + 3);
  36707. // Four vertices per face.
  36708. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36709. positions.push(vertex.x, vertex.y, vertex.z);
  36710. normals.push(normal.x, normal.y, normal.z);
  36711. uvs.push(faceUV[index].z, faceUV[index].w);
  36712. if (faceColors) {
  36713. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36714. }
  36715. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36716. positions.push(vertex.x, vertex.y, vertex.z);
  36717. normals.push(normal.x, normal.y, normal.z);
  36718. uvs.push(faceUV[index].x, faceUV[index].w);
  36719. if (faceColors) {
  36720. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36721. }
  36722. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36723. positions.push(vertex.x, vertex.y, vertex.z);
  36724. normals.push(normal.x, normal.y, normal.z);
  36725. uvs.push(faceUV[index].x, faceUV[index].y);
  36726. if (faceColors) {
  36727. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36728. }
  36729. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36730. positions.push(vertex.x, vertex.y, vertex.z);
  36731. normals.push(normal.x, normal.y, normal.z);
  36732. uvs.push(faceUV[index].z, faceUV[index].y);
  36733. if (faceColors) {
  36734. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36735. }
  36736. }
  36737. // sides
  36738. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36739. // Result
  36740. var vertexData = new VertexData();
  36741. vertexData.indices = indices;
  36742. vertexData.positions = positions;
  36743. vertexData.normals = normals;
  36744. vertexData.uvs = uvs;
  36745. if (faceColors) {
  36746. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36747. vertexData.colors = totalColors;
  36748. }
  36749. return vertexData;
  36750. };
  36751. /**
  36752. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36753. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36754. * * segments sets the number of horizontal strips optional, default 32
  36755. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36756. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36757. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36758. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36759. * * 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
  36760. * * 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
  36761. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36762. * * 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)
  36763. * * 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)
  36764. * @returns the VertexData of the ellipsoid
  36765. */
  36766. VertexData.CreateSphere = function (options) {
  36767. var segments = options.segments || 32;
  36768. var diameterX = options.diameterX || options.diameter || 1;
  36769. var diameterY = options.diameterY || options.diameter || 1;
  36770. var diameterZ = options.diameterZ || options.diameter || 1;
  36771. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36772. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36773. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36774. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36775. var totalZRotationSteps = 2 + segments;
  36776. var totalYRotationSteps = 2 * totalZRotationSteps;
  36777. var indices = [];
  36778. var positions = [];
  36779. var normals = [];
  36780. var uvs = [];
  36781. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36782. var normalizedZ = zRotationStep / totalZRotationSteps;
  36783. var angleZ = normalizedZ * Math.PI * slice;
  36784. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36785. var normalizedY = yRotationStep / totalYRotationSteps;
  36786. var angleY = normalizedY * Math.PI * 2 * arc;
  36787. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36788. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36789. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36790. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36791. var vertex = complete.multiply(radius);
  36792. var normal = complete.divide(radius).normalize();
  36793. positions.push(vertex.x, vertex.y, vertex.z);
  36794. normals.push(normal.x, normal.y, normal.z);
  36795. uvs.push(normalizedY, normalizedZ);
  36796. }
  36797. if (zRotationStep > 0) {
  36798. var verticesCount = positions.length / 3;
  36799. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36800. indices.push((firstIndex));
  36801. indices.push((firstIndex + 1));
  36802. indices.push(firstIndex + totalYRotationSteps + 1);
  36803. indices.push((firstIndex + totalYRotationSteps + 1));
  36804. indices.push((firstIndex + 1));
  36805. indices.push((firstIndex + totalYRotationSteps + 2));
  36806. }
  36807. }
  36808. }
  36809. // Sides
  36810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36811. // Result
  36812. var vertexData = new VertexData();
  36813. vertexData.indices = indices;
  36814. vertexData.positions = positions;
  36815. vertexData.normals = normals;
  36816. vertexData.uvs = uvs;
  36817. return vertexData;
  36818. };
  36819. /**
  36820. * Creates the VertexData for a cylinder, cone or prism
  36821. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36822. * * height sets the height (y direction) of the cylinder, optional, default 2
  36823. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36824. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36825. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36826. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36827. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36828. * * 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
  36829. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36830. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36831. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36832. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36833. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36834. * * 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)
  36835. * * 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)
  36836. * @returns the VertexData of the cylinder, cone or prism
  36837. */
  36838. VertexData.CreateCylinder = function (options) {
  36839. var height = options.height || 2;
  36840. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36841. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36842. var tessellation = options.tessellation || 24;
  36843. var subdivisions = options.subdivisions || 1;
  36844. var hasRings = options.hasRings ? true : false;
  36845. var enclose = options.enclose ? true : false;
  36846. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36847. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36848. var faceUV = options.faceUV || new Array(3);
  36849. var faceColors = options.faceColors;
  36850. // default face colors and UV if undefined
  36851. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36852. var ringNb = (hasRings) ? subdivisions : 1;
  36853. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36854. var f;
  36855. for (f = 0; f < surfaceNb; f++) {
  36856. if (faceColors && faceColors[f] === undefined) {
  36857. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36858. }
  36859. }
  36860. for (f = 0; f < surfaceNb; f++) {
  36861. if (faceUV && faceUV[f] === undefined) {
  36862. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36863. }
  36864. }
  36865. var indices = new Array();
  36866. var positions = new Array();
  36867. var normals = new Array();
  36868. var uvs = new Array();
  36869. var colors = new Array();
  36870. var angle_step = Math.PI * 2 * arc / tessellation;
  36871. var angle;
  36872. var h;
  36873. var radius;
  36874. var tan = (diameterBottom - diameterTop) / 2 / height;
  36875. var ringVertex = BABYLON.Vector3.Zero();
  36876. var ringNormal = BABYLON.Vector3.Zero();
  36877. var ringFirstVertex = BABYLON.Vector3.Zero();
  36878. var ringFirstNormal = BABYLON.Vector3.Zero();
  36879. var quadNormal = BABYLON.Vector3.Zero();
  36880. var Y = BABYLON.Axis.Y;
  36881. // positions, normals, uvs
  36882. var i;
  36883. var j;
  36884. var r;
  36885. var ringIdx = 1;
  36886. var s = 1; // surface index
  36887. var cs = 0;
  36888. var v = 0;
  36889. for (i = 0; i <= subdivisions; i++) {
  36890. h = i / subdivisions;
  36891. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36892. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36893. for (r = 0; r < ringIdx; r++) {
  36894. if (hasRings) {
  36895. s += r;
  36896. }
  36897. if (enclose) {
  36898. s += 2 * r;
  36899. }
  36900. for (j = 0; j <= tessellation; j++) {
  36901. angle = j * angle_step;
  36902. // position
  36903. ringVertex.x = Math.cos(-angle) * radius;
  36904. ringVertex.y = -height / 2 + h * height;
  36905. ringVertex.z = Math.sin(-angle) * radius;
  36906. // normal
  36907. if (diameterTop === 0 && i === subdivisions) {
  36908. // if no top cap, reuse former normals
  36909. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36910. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36911. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36912. }
  36913. else {
  36914. ringNormal.x = ringVertex.x;
  36915. ringNormal.z = ringVertex.z;
  36916. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36917. ringNormal.normalize();
  36918. }
  36919. // keep first ring vertex values for enclose
  36920. if (j === 0) {
  36921. ringFirstVertex.copyFrom(ringVertex);
  36922. ringFirstNormal.copyFrom(ringNormal);
  36923. }
  36924. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36925. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36926. if (hasRings) {
  36927. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36928. }
  36929. else {
  36930. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36931. }
  36932. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36933. if (faceColors) {
  36934. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36935. }
  36936. }
  36937. // if enclose, add four vertices and their dedicated normals
  36938. if (arc !== 1 && enclose) {
  36939. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36940. positions.push(0, ringVertex.y, 0);
  36941. positions.push(0, ringVertex.y, 0);
  36942. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36943. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36944. quadNormal.normalize();
  36945. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36946. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36947. quadNormal.normalize();
  36948. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36949. if (hasRings) {
  36950. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36951. }
  36952. else {
  36953. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36954. }
  36955. uvs.push(faceUV[s + 1].x, v);
  36956. uvs.push(faceUV[s + 1].z, v);
  36957. if (hasRings) {
  36958. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36959. }
  36960. else {
  36961. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36962. }
  36963. uvs.push(faceUV[s + 2].x, v);
  36964. uvs.push(faceUV[s + 2].z, v);
  36965. if (faceColors) {
  36966. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36967. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36968. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36969. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36970. }
  36971. }
  36972. if (cs !== s) {
  36973. cs = s;
  36974. }
  36975. }
  36976. }
  36977. // indices
  36978. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36979. var s;
  36980. i = 0;
  36981. for (s = 0; s < subdivisions; s++) {
  36982. var i0 = 0;
  36983. var i1 = 0;
  36984. var i2 = 0;
  36985. var i3 = 0;
  36986. for (j = 0; j < tessellation; j++) {
  36987. i0 = i * (e + 1) + j;
  36988. i1 = (i + 1) * (e + 1) + j;
  36989. i2 = i * (e + 1) + (j + 1);
  36990. i3 = (i + 1) * (e + 1) + (j + 1);
  36991. indices.push(i0, i1, i2);
  36992. indices.push(i3, i2, i1);
  36993. }
  36994. if (arc !== 1 && enclose) { // if enclose, add two quads
  36995. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36996. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36997. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36998. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36999. }
  37000. i = (hasRings) ? (i + 2) : (i + 1);
  37001. }
  37002. // Caps
  37003. var createCylinderCap = function (isTop) {
  37004. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37005. if (radius === 0) {
  37006. return;
  37007. }
  37008. // Cap positions, normals & uvs
  37009. var angle;
  37010. var circleVector;
  37011. var i;
  37012. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37013. var c = null;
  37014. if (faceColors) {
  37015. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37016. }
  37017. // cap center
  37018. var vbase = positions.length / 3;
  37019. var offset = isTop ? height / 2 : -height / 2;
  37020. var center = new BABYLON.Vector3(0, offset, 0);
  37021. positions.push(center.x, center.y, center.z);
  37022. normals.push(0, isTop ? 1 : -1, 0);
  37023. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37024. if (c) {
  37025. colors.push(c.r, c.g, c.b, c.a);
  37026. }
  37027. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37028. for (i = 0; i <= tessellation; i++) {
  37029. angle = Math.PI * 2 * i * arc / tessellation;
  37030. var cos = Math.cos(-angle);
  37031. var sin = Math.sin(-angle);
  37032. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37033. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37034. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37035. normals.push(0, isTop ? 1 : -1, 0);
  37036. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37037. if (c) {
  37038. colors.push(c.r, c.g, c.b, c.a);
  37039. }
  37040. }
  37041. // Cap indices
  37042. for (i = 0; i < tessellation; i++) {
  37043. if (!isTop) {
  37044. indices.push(vbase);
  37045. indices.push(vbase + (i + 1));
  37046. indices.push(vbase + (i + 2));
  37047. }
  37048. else {
  37049. indices.push(vbase);
  37050. indices.push(vbase + (i + 2));
  37051. indices.push(vbase + (i + 1));
  37052. }
  37053. }
  37054. };
  37055. // add caps to geometry
  37056. createCylinderCap(false);
  37057. createCylinderCap(true);
  37058. // Sides
  37059. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37060. var vertexData = new VertexData();
  37061. vertexData.indices = indices;
  37062. vertexData.positions = positions;
  37063. vertexData.normals = normals;
  37064. vertexData.uvs = uvs;
  37065. if (faceColors) {
  37066. vertexData.colors = colors;
  37067. }
  37068. return vertexData;
  37069. };
  37070. /**
  37071. * Creates the VertexData for a torus
  37072. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37073. * * diameter the diameter of the torus, optional default 1
  37074. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37075. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37076. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37077. * * 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)
  37078. * * 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)
  37079. * @returns the VertexData of the torus
  37080. */
  37081. VertexData.CreateTorus = function (options) {
  37082. var indices = [];
  37083. var positions = [];
  37084. var normals = [];
  37085. var uvs = [];
  37086. var diameter = options.diameter || 1;
  37087. var thickness = options.thickness || 0.5;
  37088. var tessellation = options.tessellation || 16;
  37089. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37090. var stride = tessellation + 1;
  37091. for (var i = 0; i <= tessellation; i++) {
  37092. var u = i / tessellation;
  37093. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37094. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37095. for (var j = 0; j <= tessellation; j++) {
  37096. var v = 1 - j / tessellation;
  37097. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37098. var dx = Math.cos(innerAngle);
  37099. var dy = Math.sin(innerAngle);
  37100. // Create a vertex.
  37101. var normal = new BABYLON.Vector3(dx, dy, 0);
  37102. var position = normal.scale(thickness / 2);
  37103. var textureCoordinate = new BABYLON.Vector2(u, v);
  37104. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37105. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37106. positions.push(position.x, position.y, position.z);
  37107. normals.push(normal.x, normal.y, normal.z);
  37108. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37109. // And create indices for two triangles.
  37110. var nextI = (i + 1) % stride;
  37111. var nextJ = (j + 1) % stride;
  37112. indices.push(i * stride + j);
  37113. indices.push(i * stride + nextJ);
  37114. indices.push(nextI * stride + j);
  37115. indices.push(i * stride + nextJ);
  37116. indices.push(nextI * stride + nextJ);
  37117. indices.push(nextI * stride + j);
  37118. }
  37119. }
  37120. // Sides
  37121. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37122. // Result
  37123. var vertexData = new VertexData();
  37124. vertexData.indices = indices;
  37125. vertexData.positions = positions;
  37126. vertexData.normals = normals;
  37127. vertexData.uvs = uvs;
  37128. return vertexData;
  37129. };
  37130. /**
  37131. * Creates the VertexData of the LineSystem
  37132. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37133. * - lines an array of lines, each line being an array of successive Vector3
  37134. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37135. * @returns the VertexData of the LineSystem
  37136. */
  37137. VertexData.CreateLineSystem = function (options) {
  37138. var indices = [];
  37139. var positions = [];
  37140. var lines = options.lines;
  37141. var colors = options.colors;
  37142. var vertexColors = [];
  37143. var idx = 0;
  37144. for (var l = 0; l < lines.length; l++) {
  37145. var points = lines[l];
  37146. for (var index = 0; index < points.length; index++) {
  37147. positions.push(points[index].x, points[index].y, points[index].z);
  37148. if (colors) {
  37149. var color = colors[l];
  37150. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37151. }
  37152. if (index > 0) {
  37153. indices.push(idx - 1);
  37154. indices.push(idx);
  37155. }
  37156. idx++;
  37157. }
  37158. }
  37159. var vertexData = new VertexData();
  37160. vertexData.indices = indices;
  37161. vertexData.positions = positions;
  37162. if (colors) {
  37163. vertexData.colors = vertexColors;
  37164. }
  37165. return vertexData;
  37166. };
  37167. /**
  37168. * Create the VertexData for a DashedLines
  37169. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37170. * - points an array successive Vector3
  37171. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37172. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37173. * - dashNb the intended total number of dashes, optional, default 200
  37174. * @returns the VertexData for the DashedLines
  37175. */
  37176. VertexData.CreateDashedLines = function (options) {
  37177. var dashSize = options.dashSize || 3;
  37178. var gapSize = options.gapSize || 1;
  37179. var dashNb = options.dashNb || 200;
  37180. var points = options.points;
  37181. var positions = new Array();
  37182. var indices = new Array();
  37183. var curvect = BABYLON.Vector3.Zero();
  37184. var lg = 0;
  37185. var nb = 0;
  37186. var shft = 0;
  37187. var dashshft = 0;
  37188. var curshft = 0;
  37189. var idx = 0;
  37190. var i = 0;
  37191. for (i = 0; i < points.length - 1; i++) {
  37192. points[i + 1].subtractToRef(points[i], curvect);
  37193. lg += curvect.length();
  37194. }
  37195. shft = lg / dashNb;
  37196. dashshft = dashSize * shft / (dashSize + gapSize);
  37197. for (i = 0; i < points.length - 1; i++) {
  37198. points[i + 1].subtractToRef(points[i], curvect);
  37199. nb = Math.floor(curvect.length() / shft);
  37200. curvect.normalize();
  37201. for (var j = 0; j < nb; j++) {
  37202. curshft = shft * j;
  37203. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37204. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37205. indices.push(idx, idx + 1);
  37206. idx += 2;
  37207. }
  37208. }
  37209. // Result
  37210. var vertexData = new VertexData();
  37211. vertexData.positions = positions;
  37212. vertexData.indices = indices;
  37213. return vertexData;
  37214. };
  37215. /**
  37216. * Creates the VertexData for a Ground
  37217. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37218. * - width the width (x direction) of the ground, optional, default 1
  37219. * - height the height (z direction) of the ground, optional, default 1
  37220. * - subdivisions the number of subdivisions per side, optional, default 1
  37221. * @returns the VertexData of the Ground
  37222. */
  37223. VertexData.CreateGround = function (options) {
  37224. var indices = [];
  37225. var positions = [];
  37226. var normals = [];
  37227. var uvs = [];
  37228. var row, col;
  37229. var width = options.width || 1;
  37230. var height = options.height || 1;
  37231. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37232. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37233. for (row = 0; row <= subdivisionsY; row++) {
  37234. for (col = 0; col <= subdivisionsX; col++) {
  37235. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37236. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37237. positions.push(position.x, position.y, position.z);
  37238. normals.push(normal.x, normal.y, normal.z);
  37239. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37240. }
  37241. }
  37242. for (row = 0; row < subdivisionsY; row++) {
  37243. for (col = 0; col < subdivisionsX; col++) {
  37244. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37245. indices.push(col + 1 + row * (subdivisionsX + 1));
  37246. indices.push(col + row * (subdivisionsX + 1));
  37247. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37248. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37249. indices.push(col + row * (subdivisionsX + 1));
  37250. }
  37251. }
  37252. // Result
  37253. var vertexData = new VertexData();
  37254. vertexData.indices = indices;
  37255. vertexData.positions = positions;
  37256. vertexData.normals = normals;
  37257. vertexData.uvs = uvs;
  37258. return vertexData;
  37259. };
  37260. /**
  37261. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37262. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37263. * * xmin the ground minimum X coordinate, optional, default -1
  37264. * * zmin the ground minimum Z coordinate, optional, default -1
  37265. * * xmax the ground maximum X coordinate, optional, default 1
  37266. * * zmax the ground maximum Z coordinate, optional, default 1
  37267. * * 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}
  37268. * * 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}
  37269. * @returns the VertexData of the TiledGround
  37270. */
  37271. VertexData.CreateTiledGround = function (options) {
  37272. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37273. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37274. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37275. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37276. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37277. var precision = options.precision || { w: 1, h: 1 };
  37278. var indices = new Array();
  37279. var positions = new Array();
  37280. var normals = new Array();
  37281. var uvs = new Array();
  37282. var row, col, tileRow, tileCol;
  37283. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37284. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37285. precision.w = (precision.w < 1) ? 1 : precision.w;
  37286. precision.h = (precision.h < 1) ? 1 : precision.h;
  37287. var tileSize = {
  37288. 'w': (xmax - xmin) / subdivisions.w,
  37289. 'h': (zmax - zmin) / subdivisions.h
  37290. };
  37291. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37292. // Indices
  37293. var base = positions.length / 3;
  37294. var rowLength = precision.w + 1;
  37295. for (row = 0; row < precision.h; row++) {
  37296. for (col = 0; col < precision.w; col++) {
  37297. var square = [
  37298. base + col + row * rowLength,
  37299. base + (col + 1) + row * rowLength,
  37300. base + (col + 1) + (row + 1) * rowLength,
  37301. base + col + (row + 1) * rowLength
  37302. ];
  37303. indices.push(square[1]);
  37304. indices.push(square[2]);
  37305. indices.push(square[3]);
  37306. indices.push(square[0]);
  37307. indices.push(square[1]);
  37308. indices.push(square[3]);
  37309. }
  37310. }
  37311. // Position, normals and uvs
  37312. var position = BABYLON.Vector3.Zero();
  37313. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37314. for (row = 0; row <= precision.h; row++) {
  37315. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37316. for (col = 0; col <= precision.w; col++) {
  37317. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37318. position.y = 0;
  37319. positions.push(position.x, position.y, position.z);
  37320. normals.push(normal.x, normal.y, normal.z);
  37321. uvs.push(col / precision.w, row / precision.h);
  37322. }
  37323. }
  37324. }
  37325. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37326. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37327. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37328. }
  37329. }
  37330. // Result
  37331. var vertexData = new VertexData();
  37332. vertexData.indices = indices;
  37333. vertexData.positions = positions;
  37334. vertexData.normals = normals;
  37335. vertexData.uvs = uvs;
  37336. return vertexData;
  37337. };
  37338. /**
  37339. * Creates the VertexData of the Ground designed from a heightmap
  37340. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37341. * * width the width (x direction) of the ground
  37342. * * height the height (z direction) of the ground
  37343. * * subdivisions the number of subdivisions per side
  37344. * * minHeight the minimum altitude on the ground, optional, default 0
  37345. * * maxHeight the maximum altitude on the ground, optional default 1
  37346. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37347. * * buffer the array holding the image color data
  37348. * * bufferWidth the width of image
  37349. * * bufferHeight the height of image
  37350. * @returns the VertexData of the Ground designed from a heightmap
  37351. */
  37352. VertexData.CreateGroundFromHeightMap = function (options) {
  37353. var indices = [];
  37354. var positions = [];
  37355. var normals = [];
  37356. var uvs = [];
  37357. var row, col;
  37358. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37359. // Vertices
  37360. for (row = 0; row <= options.subdivisions; row++) {
  37361. for (col = 0; col <= options.subdivisions; col++) {
  37362. 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));
  37363. // Compute height
  37364. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37365. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37366. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37367. var r = options.buffer[pos] / 255.0;
  37368. var g = options.buffer[pos + 1] / 255.0;
  37369. var b = options.buffer[pos + 2] / 255.0;
  37370. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37371. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37372. // Add vertex
  37373. positions.push(position.x, position.y, position.z);
  37374. normals.push(0, 0, 0);
  37375. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37376. }
  37377. }
  37378. // Indices
  37379. for (row = 0; row < options.subdivisions; row++) {
  37380. for (col = 0; col < options.subdivisions; col++) {
  37381. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37382. indices.push(col + 1 + row * (options.subdivisions + 1));
  37383. indices.push(col + row * (options.subdivisions + 1));
  37384. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37385. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37386. indices.push(col + row * (options.subdivisions + 1));
  37387. }
  37388. }
  37389. // Normals
  37390. VertexData.ComputeNormals(positions, indices, normals);
  37391. // Result
  37392. var vertexData = new VertexData();
  37393. vertexData.indices = indices;
  37394. vertexData.positions = positions;
  37395. vertexData.normals = normals;
  37396. vertexData.uvs = uvs;
  37397. return vertexData;
  37398. };
  37399. /**
  37400. * Creates the VertexData for a Plane
  37401. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37402. * * size sets the width and height of the plane to the value of size, optional default 1
  37403. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37404. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37405. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37406. * * 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)
  37407. * * 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)
  37408. * @returns the VertexData of the box
  37409. */
  37410. VertexData.CreatePlane = function (options) {
  37411. var indices = [];
  37412. var positions = [];
  37413. var normals = [];
  37414. var uvs = [];
  37415. var width = options.width || options.size || 1;
  37416. var height = options.height || options.size || 1;
  37417. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37418. // Vertices
  37419. var halfWidth = width / 2.0;
  37420. var halfHeight = height / 2.0;
  37421. positions.push(-halfWidth, -halfHeight, 0);
  37422. normals.push(0, 0, -1.0);
  37423. uvs.push(0.0, 0.0);
  37424. positions.push(halfWidth, -halfHeight, 0);
  37425. normals.push(0, 0, -1.0);
  37426. uvs.push(1.0, 0.0);
  37427. positions.push(halfWidth, halfHeight, 0);
  37428. normals.push(0, 0, -1.0);
  37429. uvs.push(1.0, 1.0);
  37430. positions.push(-halfWidth, halfHeight, 0);
  37431. normals.push(0, 0, -1.0);
  37432. uvs.push(0.0, 1.0);
  37433. // Indices
  37434. indices.push(0);
  37435. indices.push(1);
  37436. indices.push(2);
  37437. indices.push(0);
  37438. indices.push(2);
  37439. indices.push(3);
  37440. // Sides
  37441. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37442. // Result
  37443. var vertexData = new VertexData();
  37444. vertexData.indices = indices;
  37445. vertexData.positions = positions;
  37446. vertexData.normals = normals;
  37447. vertexData.uvs = uvs;
  37448. return vertexData;
  37449. };
  37450. /**
  37451. * Creates the VertexData of the Disc or regular Polygon
  37452. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37453. * * radius the radius of the disc, optional default 0.5
  37454. * * tessellation the number of polygon sides, optional, default 64
  37455. * * 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
  37456. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37457. * * 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)
  37458. * * 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)
  37459. * @returns the VertexData of the box
  37460. */
  37461. VertexData.CreateDisc = function (options) {
  37462. var positions = new Array();
  37463. var indices = new Array();
  37464. var normals = new Array();
  37465. var uvs = new Array();
  37466. var radius = options.radius || 0.5;
  37467. var tessellation = options.tessellation || 64;
  37468. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37469. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37470. // positions and uvs
  37471. positions.push(0, 0, 0); // disc center first
  37472. uvs.push(0.5, 0.5);
  37473. var theta = Math.PI * 2 * arc;
  37474. var step = theta / tessellation;
  37475. for (var a = 0; a < theta; a += step) {
  37476. var x = Math.cos(a);
  37477. var y = Math.sin(a);
  37478. var u = (x + 1) / 2;
  37479. var v = (1 - y) / 2;
  37480. positions.push(radius * x, radius * y, 0);
  37481. uvs.push(u, v);
  37482. }
  37483. if (arc === 1) {
  37484. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37485. uvs.push(uvs[2], uvs[3]);
  37486. }
  37487. //indices
  37488. var vertexNb = positions.length / 3;
  37489. for (var i = 1; i < vertexNb - 1; i++) {
  37490. indices.push(i + 1, 0, i);
  37491. }
  37492. // result
  37493. VertexData.ComputeNormals(positions, indices, normals);
  37494. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37495. var vertexData = new VertexData();
  37496. vertexData.indices = indices;
  37497. vertexData.positions = positions;
  37498. vertexData.normals = normals;
  37499. vertexData.uvs = uvs;
  37500. return vertexData;
  37501. };
  37502. /**
  37503. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37504. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37505. * @param polygon a mesh built from polygonTriangulation.build()
  37506. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37507. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37508. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37509. * @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)
  37510. * @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)
  37511. * @returns the VertexData of the Polygon
  37512. */
  37513. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37514. var faceUV = fUV || new Array(3);
  37515. var faceColors = fColors;
  37516. var colors = [];
  37517. // default face colors and UV if undefined
  37518. for (var f = 0; f < 3; f++) {
  37519. if (faceUV[f] === undefined) {
  37520. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37521. }
  37522. if (faceColors && faceColors[f] === undefined) {
  37523. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37524. }
  37525. }
  37526. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37527. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37528. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37529. var indices = polygon.getIndices();
  37530. // set face colours and textures
  37531. var idx = 0;
  37532. var face = 0;
  37533. for (var index = 0; index < normals.length; index += 3) {
  37534. //Edge Face no. 1
  37535. if (Math.abs(normals[index + 1]) < 0.001) {
  37536. face = 1;
  37537. }
  37538. //Top Face no. 0
  37539. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37540. face = 0;
  37541. }
  37542. //Bottom Face no. 2
  37543. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37544. face = 2;
  37545. }
  37546. idx = index / 3;
  37547. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37548. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37549. if (faceColors) {
  37550. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37551. }
  37552. }
  37553. // sides
  37554. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37555. // Result
  37556. var vertexData = new VertexData();
  37557. vertexData.indices = indices;
  37558. vertexData.positions = positions;
  37559. vertexData.normals = normals;
  37560. vertexData.uvs = uvs;
  37561. if (faceColors) {
  37562. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37563. vertexData.colors = totalColors;
  37564. }
  37565. return vertexData;
  37566. };
  37567. /**
  37568. * Creates the VertexData of the IcoSphere
  37569. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37570. * * radius the radius of the IcoSphere, optional default 1
  37571. * * radiusX allows stretching in the x direction, optional, default radius
  37572. * * radiusY allows stretching in the y direction, optional, default radius
  37573. * * radiusZ allows stretching in the z direction, optional, default radius
  37574. * * flat when true creates a flat shaded mesh, optional, default true
  37575. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37576. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37577. * * 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)
  37578. * * 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)
  37579. * @returns the VertexData of the IcoSphere
  37580. */
  37581. VertexData.CreateIcoSphere = function (options) {
  37582. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37583. var radius = options.radius || 1;
  37584. var flat = (options.flat === undefined) ? true : options.flat;
  37585. var subdivisions = options.subdivisions || 4;
  37586. var radiusX = options.radiusX || radius;
  37587. var radiusY = options.radiusY || radius;
  37588. var radiusZ = options.radiusZ || radius;
  37589. var t = (1 + Math.sqrt(5)) / 2;
  37590. // 12 vertex x,y,z
  37591. var ico_vertices = [
  37592. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37593. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37594. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37595. ];
  37596. // index of 3 vertex makes a face of icopshere
  37597. var ico_indices = [
  37598. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37599. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37600. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37601. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37602. ];
  37603. // vertex for uv have aliased position, not for UV
  37604. var vertices_unalias_id = [
  37605. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37606. // vertex alias
  37607. 0,
  37608. 2,
  37609. 3,
  37610. 3,
  37611. 3,
  37612. 4,
  37613. 7,
  37614. 8,
  37615. 9,
  37616. 9,
  37617. 10,
  37618. 11 // 23: B + 12
  37619. ];
  37620. // uv as integer step (not pixels !)
  37621. var ico_vertexuv = [
  37622. 5, 1, 3, 1, 6, 4, 0, 0,
  37623. 5, 3, 4, 2, 2, 2, 4, 0,
  37624. 2, 0, 1, 1, 6, 0, 6, 2,
  37625. // vertex alias (for same vertex on different faces)
  37626. 0, 4,
  37627. 3, 3,
  37628. 4, 4,
  37629. 3, 1,
  37630. 4, 2,
  37631. 4, 4,
  37632. 0, 2,
  37633. 1, 1,
  37634. 2, 2,
  37635. 3, 3,
  37636. 1, 3,
  37637. 2, 4 // 23: B + 12
  37638. ];
  37639. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37640. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37641. // First island of uv mapping
  37642. // v = 4h 3+ 2
  37643. // v = 3h 9+ 4
  37644. // v = 2h 9+ 5 B
  37645. // v = 1h 9 1 0
  37646. // v = 0h 3 8 7 A
  37647. // u = 0 1 2 3 4 5 6 *a
  37648. // Second island of uv mapping
  37649. // v = 4h 0+ B+ 4+
  37650. // v = 3h A+ 2+
  37651. // v = 2h 7+ 6 3+
  37652. // v = 1h 8+ 3+
  37653. // v = 0h
  37654. // u = 0 1 2 3 4 5 6 *a
  37655. // Face layout on texture UV mapping
  37656. // ============
  37657. // \ 4 /\ 16 / ======
  37658. // \ / \ / /\ 11 /
  37659. // \/ 7 \/ / \ /
  37660. // ======= / 10 \/
  37661. // /\ 17 /\ =======
  37662. // / \ / \ \ 15 /\
  37663. // / 8 \/ 12 \ \ / \
  37664. // ============ \/ 6 \
  37665. // \ 18 /\ ============
  37666. // \ / \ \ 5 /\ 0 /
  37667. // \/ 13 \ \ / \ /
  37668. // ======= \/ 1 \/
  37669. // =============
  37670. // /\ 19 /\ 2 /\
  37671. // / \ / \ / \
  37672. // / 14 \/ 9 \/ 3 \
  37673. // ===================
  37674. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37675. var ustep = 138 / 1024;
  37676. var vstep = 239 / 1024;
  37677. var uoffset = 60 / 1024;
  37678. var voffset = 26 / 1024;
  37679. // Second island should have margin, not to touch the first island
  37680. // avoid any borderline artefact in pixel rounding
  37681. var island_u_offset = -40 / 1024;
  37682. var island_v_offset = +20 / 1024;
  37683. // face is either island 0 or 1 :
  37684. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37685. var island = [
  37686. 0, 0, 0, 0, 1,
  37687. 0, 0, 1, 1, 0,
  37688. 0, 0, 1, 1, 0,
  37689. 0, 1, 1, 1, 0 // 15 - 19
  37690. ];
  37691. var indices = new Array();
  37692. var positions = new Array();
  37693. var normals = new Array();
  37694. var uvs = new Array();
  37695. var current_indice = 0;
  37696. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37697. var face_vertex_pos = new Array(3);
  37698. var face_vertex_uv = new Array(3);
  37699. var v012;
  37700. for (v012 = 0; v012 < 3; v012++) {
  37701. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37702. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37703. }
  37704. // create all with normals
  37705. for (var face = 0; face < 20; face++) {
  37706. // 3 vertex per face
  37707. for (v012 = 0; v012 < 3; v012++) {
  37708. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37709. var v_id = ico_indices[3 * face + v012];
  37710. // vertex have 3D position (x,y,z)
  37711. 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]);
  37712. // Normalize to get normal, then scale to radius
  37713. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37714. // uv Coordinates from vertex ID
  37715. 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);
  37716. }
  37717. // Subdivide the face (interpolate pos, norm, uv)
  37718. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37719. // - norm is linear interpolation of vertex corner normal
  37720. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37721. // - uv is linear interpolation
  37722. //
  37723. // Topology is as below for sub-divide by 2
  37724. // vertex shown as v0,v1,v2
  37725. // interp index is i1 to progress in range [v0,v1[
  37726. // interp index is i2 to progress in range [v0,v2[
  37727. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37728. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37729. //
  37730. //
  37731. // i2 v2
  37732. // ^ ^
  37733. // / / \
  37734. // / / \
  37735. // / / \
  37736. // / / (0,1) \
  37737. // / #---------\
  37738. // / / \ (0,0)'/ \
  37739. // / / \ / \
  37740. // / / \ / \
  37741. // / / (0,0) \ / (1,0) \
  37742. // / #---------#---------\
  37743. // v0 v1
  37744. //
  37745. // --------------------> i1
  37746. //
  37747. // interp of (i1,i2):
  37748. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37749. // along i1 : lerp(x0,x1, i1/(S-i2))
  37750. //
  37751. // centroid of triangle is needed to get help normal computation
  37752. // (c1,c2) are used for centroid location
  37753. var interp_vertex = function (i1, i2, c1, c2) {
  37754. // vertex is interpolated from
  37755. // - face_vertex_pos[0..2]
  37756. // - face_vertex_uv[0..2]
  37757. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37758. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37759. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37760. pos_interp.normalize();
  37761. var vertex_normal;
  37762. if (flat) {
  37763. // in flat mode, recalculate normal as face centroid normal
  37764. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37765. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37766. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37767. }
  37768. else {
  37769. // in smooth mode, recalculate normal from each single vertex position
  37770. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37771. }
  37772. // Vertex normal need correction due to X,Y,Z radius scaling
  37773. vertex_normal.x /= radiusX;
  37774. vertex_normal.y /= radiusY;
  37775. vertex_normal.z /= radiusZ;
  37776. vertex_normal.normalize();
  37777. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37778. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37779. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37780. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37781. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37782. uvs.push(uv_interp.x, uv_interp.y);
  37783. // push each vertex has member of a face
  37784. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37785. indices.push(current_indice);
  37786. current_indice++;
  37787. };
  37788. for (var i2 = 0; i2 < subdivisions; i2++) {
  37789. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37790. // face : (i1,i2) for /\ :
  37791. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37792. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37793. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37794. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37795. if (i1 + i2 + 1 < subdivisions) {
  37796. // face : (i1,i2)' for \/ :
  37797. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37798. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37799. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37800. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37801. }
  37802. }
  37803. }
  37804. }
  37805. // Sides
  37806. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37807. // Result
  37808. var vertexData = new VertexData();
  37809. vertexData.indices = indices;
  37810. vertexData.positions = positions;
  37811. vertexData.normals = normals;
  37812. vertexData.uvs = uvs;
  37813. return vertexData;
  37814. };
  37815. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37816. /**
  37817. * Creates the VertexData for a Polyhedron
  37818. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37819. * * type provided types are:
  37820. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37821. * * 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)
  37822. * * size the size of the IcoSphere, optional default 1
  37823. * * sizeX allows stretching in the x direction, optional, default size
  37824. * * sizeY allows stretching in the y direction, optional, default size
  37825. * * sizeZ allows stretching in the z direction, optional, default size
  37826. * * 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
  37827. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37828. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37829. * * flat when true creates a flat shaded mesh, optional, default true
  37830. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37831. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37832. * * 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)
  37833. * * 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)
  37834. * @returns the VertexData of the Polyhedron
  37835. */
  37836. VertexData.CreatePolyhedron = function (options) {
  37837. // provided polyhedron types :
  37838. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37839. // 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)
  37840. var polyhedra = [];
  37841. 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]] };
  37842. 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]] };
  37843. polyhedra[2] = {
  37844. 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]],
  37845. 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]]
  37846. };
  37847. polyhedra[3] = {
  37848. 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]],
  37849. 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]]
  37850. };
  37851. polyhedra[4] = {
  37852. 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]],
  37853. 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]]
  37854. };
  37855. 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]] };
  37856. 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]] };
  37857. 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]] };
  37858. 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]] };
  37859. 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]] };
  37860. 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]] };
  37861. 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]] };
  37862. 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]] };
  37863. 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]] };
  37864. polyhedra[14] = {
  37865. 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]],
  37866. 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]]
  37867. };
  37868. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37869. var size = options.size;
  37870. var sizeX = options.sizeX || size || 1;
  37871. var sizeY = options.sizeY || size || 1;
  37872. var sizeZ = options.sizeZ || size || 1;
  37873. var data = options.custom || polyhedra[type];
  37874. var nbfaces = data.face.length;
  37875. var faceUV = options.faceUV || new Array(nbfaces);
  37876. var faceColors = options.faceColors;
  37877. var flat = (options.flat === undefined) ? true : options.flat;
  37878. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37879. var positions = new Array();
  37880. var indices = new Array();
  37881. var normals = new Array();
  37882. var uvs = new Array();
  37883. var colors = new Array();
  37884. var index = 0;
  37885. var faceIdx = 0; // face cursor in the array "indexes"
  37886. var indexes = new Array();
  37887. var i = 0;
  37888. var f = 0;
  37889. var u, v, ang, x, y, tmp;
  37890. // default face colors and UV if undefined
  37891. if (flat) {
  37892. for (f = 0; f < nbfaces; f++) {
  37893. if (faceColors && faceColors[f] === undefined) {
  37894. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37895. }
  37896. if (faceUV && faceUV[f] === undefined) {
  37897. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37898. }
  37899. }
  37900. }
  37901. if (!flat) {
  37902. for (i = 0; i < data.vertex.length; i++) {
  37903. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37904. uvs.push(0, 0);
  37905. }
  37906. for (f = 0; f < nbfaces; f++) {
  37907. for (i = 0; i < data.face[f].length - 2; i++) {
  37908. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37909. }
  37910. }
  37911. }
  37912. else {
  37913. for (f = 0; f < nbfaces; f++) {
  37914. var fl = data.face[f].length; // number of vertices of the current face
  37915. ang = 2 * Math.PI / fl;
  37916. x = 0.5 * Math.tan(ang / 2);
  37917. y = 0.5;
  37918. // positions, uvs, colors
  37919. for (i = 0; i < fl; i++) {
  37920. // positions
  37921. 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);
  37922. indexes.push(index);
  37923. index++;
  37924. // uvs
  37925. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37926. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37927. uvs.push(u, v);
  37928. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37929. y = x * Math.sin(ang) + y * Math.cos(ang);
  37930. x = tmp;
  37931. // colors
  37932. if (faceColors) {
  37933. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37934. }
  37935. }
  37936. // indices from indexes
  37937. for (i = 0; i < fl - 2; i++) {
  37938. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37939. }
  37940. faceIdx += fl;
  37941. }
  37942. }
  37943. VertexData.ComputeNormals(positions, indices, normals);
  37944. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37945. var vertexData = new VertexData();
  37946. vertexData.positions = positions;
  37947. vertexData.indices = indices;
  37948. vertexData.normals = normals;
  37949. vertexData.uvs = uvs;
  37950. if (faceColors && flat) {
  37951. vertexData.colors = colors;
  37952. }
  37953. return vertexData;
  37954. };
  37955. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37956. /**
  37957. * Creates the VertexData for a TorusKnot
  37958. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37959. * * radius the radius of the torus knot, optional, default 2
  37960. * * tube the thickness of the tube, optional, default 0.5
  37961. * * radialSegments the number of sides on each tube segments, optional, default 32
  37962. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37963. * * p the number of windings around the z axis, optional, default 2
  37964. * * q the number of windings around the x axis, optional, default 3
  37965. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37966. * * 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)
  37967. * * 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)
  37968. * @returns the VertexData of the Torus Knot
  37969. */
  37970. VertexData.CreateTorusKnot = function (options) {
  37971. var indices = new Array();
  37972. var positions = new Array();
  37973. var normals = new Array();
  37974. var uvs = new Array();
  37975. var radius = options.radius || 2;
  37976. var tube = options.tube || 0.5;
  37977. var radialSegments = options.radialSegments || 32;
  37978. var tubularSegments = options.tubularSegments || 32;
  37979. var p = options.p || 2;
  37980. var q = options.q || 3;
  37981. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37982. // Helper
  37983. var getPos = function (angle) {
  37984. var cu = Math.cos(angle);
  37985. var su = Math.sin(angle);
  37986. var quOverP = q / p * angle;
  37987. var cs = Math.cos(quOverP);
  37988. var tx = radius * (2 + cs) * 0.5 * cu;
  37989. var ty = radius * (2 + cs) * su * 0.5;
  37990. var tz = radius * Math.sin(quOverP) * 0.5;
  37991. return new BABYLON.Vector3(tx, ty, tz);
  37992. };
  37993. // Vertices
  37994. var i;
  37995. var j;
  37996. for (i = 0; i <= radialSegments; i++) {
  37997. var modI = i % radialSegments;
  37998. var u = modI / radialSegments * 2 * p * Math.PI;
  37999. var p1 = getPos(u);
  38000. var p2 = getPos(u + 0.01);
  38001. var tang = p2.subtract(p1);
  38002. var n = p2.add(p1);
  38003. var bitan = BABYLON.Vector3.Cross(tang, n);
  38004. n = BABYLON.Vector3.Cross(bitan, tang);
  38005. bitan.normalize();
  38006. n.normalize();
  38007. for (j = 0; j < tubularSegments; j++) {
  38008. var modJ = j % tubularSegments;
  38009. var v = modJ / tubularSegments * 2 * Math.PI;
  38010. var cx = -tube * Math.cos(v);
  38011. var cy = tube * Math.sin(v);
  38012. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38013. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38014. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38015. uvs.push(i / radialSegments);
  38016. uvs.push(j / tubularSegments);
  38017. }
  38018. }
  38019. for (i = 0; i < radialSegments; i++) {
  38020. for (j = 0; j < tubularSegments; j++) {
  38021. var jNext = (j + 1) % tubularSegments;
  38022. var a = i * tubularSegments + j;
  38023. var b = (i + 1) * tubularSegments + j;
  38024. var c = (i + 1) * tubularSegments + jNext;
  38025. var d = i * tubularSegments + jNext;
  38026. indices.push(d);
  38027. indices.push(b);
  38028. indices.push(a);
  38029. indices.push(d);
  38030. indices.push(c);
  38031. indices.push(b);
  38032. }
  38033. }
  38034. // Normals
  38035. VertexData.ComputeNormals(positions, indices, normals);
  38036. // Sides
  38037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38038. // Result
  38039. var vertexData = new VertexData();
  38040. vertexData.indices = indices;
  38041. vertexData.positions = positions;
  38042. vertexData.normals = normals;
  38043. vertexData.uvs = uvs;
  38044. return vertexData;
  38045. };
  38046. // Tools
  38047. /**
  38048. * Compute normals for given positions and indices
  38049. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38050. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38051. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38052. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38053. * * facetNormals : optional array of facet normals (vector3)
  38054. * * facetPositions : optional array of facet positions (vector3)
  38055. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38056. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38057. * * bInfo : optional bounding info, required for facetPartitioning computation
  38058. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38059. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38060. * * useRightHandedSystem: optional boolean to for right handed system computation
  38061. * * depthSort : optional boolean to enable the facet depth sort computation
  38062. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38063. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38064. */
  38065. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38066. // temporary scalar variables
  38067. var index = 0; // facet index
  38068. var p1p2x = 0.0; // p1p2 vector x coordinate
  38069. var p1p2y = 0.0; // p1p2 vector y coordinate
  38070. var p1p2z = 0.0; // p1p2 vector z coordinate
  38071. var p3p2x = 0.0; // p3p2 vector x coordinate
  38072. var p3p2y = 0.0; // p3p2 vector y coordinate
  38073. var p3p2z = 0.0; // p3p2 vector z coordinate
  38074. var faceNormalx = 0.0; // facet normal x coordinate
  38075. var faceNormaly = 0.0; // facet normal y coordinate
  38076. var faceNormalz = 0.0; // facet normal z coordinate
  38077. var length = 0.0; // facet normal length before normalization
  38078. var v1x = 0; // vector1 x index in the positions array
  38079. var v1y = 0; // vector1 y index in the positions array
  38080. var v1z = 0; // vector1 z index in the positions array
  38081. var v2x = 0; // vector2 x index in the positions array
  38082. var v2y = 0; // vector2 y index in the positions array
  38083. var v2z = 0; // vector2 z index in the positions array
  38084. var v3x = 0; // vector3 x index in the positions array
  38085. var v3y = 0; // vector3 y index in the positions array
  38086. var v3z = 0; // vector3 z index in the positions array
  38087. var computeFacetNormals = false;
  38088. var computeFacetPositions = false;
  38089. var computeFacetPartitioning = false;
  38090. var computeDepthSort = false;
  38091. var faceNormalSign = 1;
  38092. var ratio = 0;
  38093. var distanceTo = null;
  38094. if (options) {
  38095. computeFacetNormals = (options.facetNormals) ? true : false;
  38096. computeFacetPositions = (options.facetPositions) ? true : false;
  38097. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38098. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38099. ratio = options.ratio || 0;
  38100. computeDepthSort = (options.depthSort) ? true : false;
  38101. distanceTo = (options.distanceTo);
  38102. if (computeDepthSort) {
  38103. if (distanceTo === undefined) {
  38104. distanceTo = BABYLON.Vector3.Zero();
  38105. }
  38106. var depthSortedFacets = options.depthSortedFacets;
  38107. }
  38108. }
  38109. // facetPartitioning reinit if needed
  38110. var xSubRatio = 0;
  38111. var ySubRatio = 0;
  38112. var zSubRatio = 0;
  38113. var subSq = 0;
  38114. if (computeFacetPartitioning && options && options.bbSize) {
  38115. var ox = 0; // X partitioning index for facet position
  38116. var oy = 0; // Y partinioning index for facet position
  38117. var oz = 0; // Z partinioning index for facet position
  38118. var b1x = 0; // X partitioning index for facet v1 vertex
  38119. var b1y = 0; // Y partitioning index for facet v1 vertex
  38120. var b1z = 0; // z partitioning index for facet v1 vertex
  38121. var b2x = 0; // X partitioning index for facet v2 vertex
  38122. var b2y = 0; // Y partitioning index for facet v2 vertex
  38123. var b2z = 0; // Z partitioning index for facet v2 vertex
  38124. var b3x = 0; // X partitioning index for facet v3 vertex
  38125. var b3y = 0; // Y partitioning index for facet v3 vertex
  38126. var b3z = 0; // Z partitioning index for facet v3 vertex
  38127. var block_idx_o = 0; // facet barycenter block index
  38128. var block_idx_v1 = 0; // v1 vertex block index
  38129. var block_idx_v2 = 0; // v2 vertex block index
  38130. var block_idx_v3 = 0; // v3 vertex block index
  38131. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38132. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38133. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38134. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38135. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38136. subSq = options.subDiv.max * options.subDiv.max;
  38137. options.facetPartitioning.length = 0;
  38138. }
  38139. // reset the normals
  38140. for (index = 0; index < positions.length; index++) {
  38141. normals[index] = 0.0;
  38142. }
  38143. // Loop : 1 indice triplet = 1 facet
  38144. var nbFaces = (indices.length / 3) | 0;
  38145. for (index = 0; index < nbFaces; index++) {
  38146. // get the indexes of the coordinates of each vertex of the facet
  38147. v1x = indices[index * 3] * 3;
  38148. v1y = v1x + 1;
  38149. v1z = v1x + 2;
  38150. v2x = indices[index * 3 + 1] * 3;
  38151. v2y = v2x + 1;
  38152. v2z = v2x + 2;
  38153. v3x = indices[index * 3 + 2] * 3;
  38154. v3y = v3x + 1;
  38155. v3z = v3x + 2;
  38156. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38157. p1p2y = positions[v1y] - positions[v2y];
  38158. p1p2z = positions[v1z] - positions[v2z];
  38159. p3p2x = positions[v3x] - positions[v2x];
  38160. p3p2y = positions[v3y] - positions[v2y];
  38161. p3p2z = positions[v3z] - positions[v2z];
  38162. // compute the face normal with the cross product
  38163. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38164. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38165. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38166. // normalize this normal and store it in the array facetData
  38167. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38168. length = (length === 0) ? 1.0 : length;
  38169. faceNormalx /= length;
  38170. faceNormaly /= length;
  38171. faceNormalz /= length;
  38172. if (computeFacetNormals && options) {
  38173. options.facetNormals[index].x = faceNormalx;
  38174. options.facetNormals[index].y = faceNormaly;
  38175. options.facetNormals[index].z = faceNormalz;
  38176. }
  38177. if (computeFacetPositions && options) {
  38178. // compute and the facet barycenter coordinates in the array facetPositions
  38179. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38180. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38181. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38182. }
  38183. if (computeFacetPartitioning && options) {
  38184. // store the facet indexes in arrays in the main facetPartitioning array :
  38185. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38186. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38187. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38188. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38189. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38190. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38191. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38192. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38193. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38194. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38195. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38196. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38197. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38198. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38199. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38200. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38201. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38202. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38203. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38204. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38205. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38206. // push each facet index in each block containing the vertex
  38207. options.facetPartitioning[block_idx_v1].push(index);
  38208. if (block_idx_v2 != block_idx_v1) {
  38209. options.facetPartitioning[block_idx_v2].push(index);
  38210. }
  38211. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38212. options.facetPartitioning[block_idx_v3].push(index);
  38213. }
  38214. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38215. options.facetPartitioning[block_idx_o].push(index);
  38216. }
  38217. }
  38218. if (computeDepthSort && options && options.facetPositions) {
  38219. var dsf = depthSortedFacets[index];
  38220. dsf.ind = index * 3;
  38221. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38222. }
  38223. // compute the normals anyway
  38224. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38225. normals[v1y] += faceNormaly;
  38226. normals[v1z] += faceNormalz;
  38227. normals[v2x] += faceNormalx;
  38228. normals[v2y] += faceNormaly;
  38229. normals[v2z] += faceNormalz;
  38230. normals[v3x] += faceNormalx;
  38231. normals[v3y] += faceNormaly;
  38232. normals[v3z] += faceNormalz;
  38233. }
  38234. // last normalization of each normal
  38235. for (index = 0; index < normals.length / 3; index++) {
  38236. faceNormalx = normals[index * 3];
  38237. faceNormaly = normals[index * 3 + 1];
  38238. faceNormalz = normals[index * 3 + 2];
  38239. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38240. length = (length === 0) ? 1.0 : length;
  38241. faceNormalx /= length;
  38242. faceNormaly /= length;
  38243. faceNormalz /= length;
  38244. normals[index * 3] = faceNormalx;
  38245. normals[index * 3 + 1] = faceNormaly;
  38246. normals[index * 3 + 2] = faceNormalz;
  38247. }
  38248. };
  38249. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38250. var li = indices.length;
  38251. var ln = normals.length;
  38252. var i;
  38253. var n;
  38254. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38255. switch (sideOrientation) {
  38256. case BABYLON.Mesh.FRONTSIDE:
  38257. // nothing changed
  38258. break;
  38259. case BABYLON.Mesh.BACKSIDE:
  38260. var tmp;
  38261. // indices
  38262. for (i = 0; i < li; i += 3) {
  38263. tmp = indices[i];
  38264. indices[i] = indices[i + 2];
  38265. indices[i + 2] = tmp;
  38266. }
  38267. // normals
  38268. for (n = 0; n < ln; n++) {
  38269. normals[n] = -normals[n];
  38270. }
  38271. break;
  38272. case BABYLON.Mesh.DOUBLESIDE:
  38273. // positions
  38274. var lp = positions.length;
  38275. var l = lp / 3;
  38276. for (var p = 0; p < lp; p++) {
  38277. positions[lp + p] = positions[p];
  38278. }
  38279. // indices
  38280. for (i = 0; i < li; i += 3) {
  38281. indices[i + li] = indices[i + 2] + l;
  38282. indices[i + 1 + li] = indices[i + 1] + l;
  38283. indices[i + 2 + li] = indices[i] + l;
  38284. }
  38285. // normals
  38286. for (n = 0; n < ln; n++) {
  38287. normals[ln + n] = -normals[n];
  38288. }
  38289. // uvs
  38290. var lu = uvs.length;
  38291. var u = 0;
  38292. for (u = 0; u < lu; u++) {
  38293. uvs[u + lu] = uvs[u];
  38294. }
  38295. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38296. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38297. u = 0;
  38298. for (i = 0; i < lu / 2; i++) {
  38299. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38300. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38301. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38302. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38303. u += 2;
  38304. }
  38305. break;
  38306. }
  38307. };
  38308. /**
  38309. * Applies VertexData created from the imported parameters to the geometry
  38310. * @param parsedVertexData the parsed data from an imported file
  38311. * @param geometry the geometry to apply the VertexData to
  38312. */
  38313. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38314. var vertexData = new VertexData();
  38315. // positions
  38316. var positions = parsedVertexData.positions;
  38317. if (positions) {
  38318. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38319. }
  38320. // normals
  38321. var normals = parsedVertexData.normals;
  38322. if (normals) {
  38323. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38324. }
  38325. // tangents
  38326. var tangents = parsedVertexData.tangents;
  38327. if (tangents) {
  38328. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38329. }
  38330. // uvs
  38331. var uvs = parsedVertexData.uvs;
  38332. if (uvs) {
  38333. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38334. }
  38335. // uv2s
  38336. var uv2s = parsedVertexData.uv2s;
  38337. if (uv2s) {
  38338. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38339. }
  38340. // uv3s
  38341. var uv3s = parsedVertexData.uv3s;
  38342. if (uv3s) {
  38343. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38344. }
  38345. // uv4s
  38346. var uv4s = parsedVertexData.uv4s;
  38347. if (uv4s) {
  38348. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38349. }
  38350. // uv5s
  38351. var uv5s = parsedVertexData.uv5s;
  38352. if (uv5s) {
  38353. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38354. }
  38355. // uv6s
  38356. var uv6s = parsedVertexData.uv6s;
  38357. if (uv6s) {
  38358. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38359. }
  38360. // colors
  38361. var colors = parsedVertexData.colors;
  38362. if (colors) {
  38363. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38364. }
  38365. // matricesIndices
  38366. var matricesIndices = parsedVertexData.matricesIndices;
  38367. if (matricesIndices) {
  38368. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38369. }
  38370. // matricesWeights
  38371. var matricesWeights = parsedVertexData.matricesWeights;
  38372. if (matricesWeights) {
  38373. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38374. }
  38375. // indices
  38376. var indices = parsedVertexData.indices;
  38377. if (indices) {
  38378. vertexData.indices = indices;
  38379. }
  38380. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38381. };
  38382. return VertexData;
  38383. }());
  38384. BABYLON.VertexData = VertexData;
  38385. })(BABYLON || (BABYLON = {}));
  38386. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38387. var BABYLON;
  38388. (function (BABYLON) {
  38389. /**
  38390. * Class used to store geometry data (vertex buffers + index buffer)
  38391. */
  38392. var Geometry = /** @class */ (function () {
  38393. /**
  38394. * Creates a new geometry
  38395. * @param id defines the unique ID
  38396. * @param scene defines the hosting scene
  38397. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38398. * @param updatable defines if geometry must be updatable (false by default)
  38399. * @param mesh defines the mesh that will be associated with the geometry
  38400. */
  38401. function Geometry(id, scene, vertexData, updatable, mesh) {
  38402. if (updatable === void 0) { updatable = false; }
  38403. if (mesh === void 0) { mesh = null; }
  38404. /**
  38405. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38406. */
  38407. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38408. this._totalVertices = 0;
  38409. this._isDisposed = false;
  38410. this._indexBufferIsUpdatable = false;
  38411. this.id = id;
  38412. this._engine = scene.getEngine();
  38413. this._meshes = [];
  38414. this._scene = scene;
  38415. //Init vertex buffer cache
  38416. this._vertexBuffers = {};
  38417. this._indices = [];
  38418. this._updatable = updatable;
  38419. // vertexData
  38420. if (vertexData) {
  38421. this.setAllVerticesData(vertexData, updatable);
  38422. }
  38423. else {
  38424. this._totalVertices = 0;
  38425. this._indices = [];
  38426. }
  38427. if (this._engine.getCaps().vertexArrayObject) {
  38428. this._vertexArrayObjects = {};
  38429. }
  38430. // applyToMesh
  38431. if (mesh) {
  38432. if (mesh.getClassName() === "LinesMesh") {
  38433. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38434. this._updateExtend();
  38435. }
  38436. this.applyToMesh(mesh);
  38437. mesh.computeWorldMatrix(true);
  38438. }
  38439. }
  38440. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38441. /**
  38442. * 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
  38443. */
  38444. get: function () {
  38445. return this._boundingBias;
  38446. },
  38447. /**
  38448. * 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
  38449. */
  38450. set: function (value) {
  38451. if (this._boundingBias && this._boundingBias.equals(value)) {
  38452. return;
  38453. }
  38454. this._boundingBias = value.clone();
  38455. this._updateBoundingInfo(true, null);
  38456. },
  38457. enumerable: true,
  38458. configurable: true
  38459. });
  38460. /**
  38461. * Static function used to attach a new empty geometry to a mesh
  38462. * @param mesh defines the mesh to attach the geometry to
  38463. * @returns the new {BABYLON.Geometry}
  38464. */
  38465. Geometry.CreateGeometryForMesh = function (mesh) {
  38466. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38467. geometry.applyToMesh(mesh);
  38468. return geometry;
  38469. };
  38470. Object.defineProperty(Geometry.prototype, "extend", {
  38471. /**
  38472. * Gets the current extend of the geometry
  38473. */
  38474. get: function () {
  38475. return this._extend;
  38476. },
  38477. enumerable: true,
  38478. configurable: true
  38479. });
  38480. /**
  38481. * Gets the hosting scene
  38482. * @returns the hosting {BABYLON.Scene}
  38483. */
  38484. Geometry.prototype.getScene = function () {
  38485. return this._scene;
  38486. };
  38487. /**
  38488. * Gets the hosting engine
  38489. * @returns the hosting {BABYLON.Engine}
  38490. */
  38491. Geometry.prototype.getEngine = function () {
  38492. return this._engine;
  38493. };
  38494. /**
  38495. * Defines if the geometry is ready to use
  38496. * @returns true if the geometry is ready to be used
  38497. */
  38498. Geometry.prototype.isReady = function () {
  38499. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38500. };
  38501. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38502. /**
  38503. * Gets a value indicating that the geometry should not be serialized
  38504. */
  38505. get: function () {
  38506. for (var index = 0; index < this._meshes.length; index++) {
  38507. if (!this._meshes[index].doNotSerialize) {
  38508. return false;
  38509. }
  38510. }
  38511. return true;
  38512. },
  38513. enumerable: true,
  38514. configurable: true
  38515. });
  38516. /** @hidden */
  38517. Geometry.prototype._rebuild = function () {
  38518. if (this._vertexArrayObjects) {
  38519. this._vertexArrayObjects = {};
  38520. }
  38521. // Index buffer
  38522. if (this._meshes.length !== 0 && this._indices) {
  38523. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38524. }
  38525. // Vertex buffers
  38526. for (var key in this._vertexBuffers) {
  38527. var vertexBuffer = this._vertexBuffers[key];
  38528. vertexBuffer._rebuild();
  38529. }
  38530. };
  38531. /**
  38532. * Affects all gemetry data in one call
  38533. * @param vertexData defines the geometry data
  38534. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38535. */
  38536. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38537. vertexData.applyToGeometry(this, updatable);
  38538. this.notifyUpdate();
  38539. };
  38540. /**
  38541. * Set specific vertex data
  38542. * @param kind defines the data kind (Position, normal, etc...)
  38543. * @param data defines the vertex data to use
  38544. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38545. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38546. */
  38547. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38548. if (updatable === void 0) { updatable = false; }
  38549. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38550. this.setVerticesBuffer(buffer);
  38551. };
  38552. /**
  38553. * Removes a specific vertex data
  38554. * @param kind defines the data kind (Position, normal, etc...)
  38555. */
  38556. Geometry.prototype.removeVerticesData = function (kind) {
  38557. if (this._vertexBuffers[kind]) {
  38558. this._vertexBuffers[kind].dispose();
  38559. delete this._vertexBuffers[kind];
  38560. }
  38561. };
  38562. /**
  38563. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38564. * @param buffer defines the vertex buffer to use
  38565. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38566. */
  38567. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38568. if (totalVertices === void 0) { totalVertices = null; }
  38569. var kind = buffer.getKind();
  38570. if (this._vertexBuffers[kind]) {
  38571. this._vertexBuffers[kind].dispose();
  38572. }
  38573. this._vertexBuffers[kind] = buffer;
  38574. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38575. var data = buffer.getData();
  38576. if (totalVertices != null) {
  38577. this._totalVertices = totalVertices;
  38578. }
  38579. else {
  38580. if (data != null) {
  38581. this._totalVertices = data.length / (buffer.byteStride / 4);
  38582. }
  38583. }
  38584. this._updateExtend(data);
  38585. this._resetPointsArrayCache();
  38586. var meshes = this._meshes;
  38587. var numOfMeshes = meshes.length;
  38588. for (var index = 0; index < numOfMeshes; index++) {
  38589. var mesh = meshes[index];
  38590. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38591. mesh._createGlobalSubMesh(false);
  38592. mesh.computeWorldMatrix(true);
  38593. }
  38594. }
  38595. this.notifyUpdate(kind);
  38596. if (this._vertexArrayObjects) {
  38597. this._disposeVertexArrayObjects();
  38598. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38599. }
  38600. };
  38601. /**
  38602. * Update a specific vertex buffer
  38603. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38604. * It will do nothing if the buffer is not updatable
  38605. * @param kind defines the data kind (Position, normal, etc...)
  38606. * @param data defines the data to use
  38607. * @param offset defines the offset in the target buffer where to store the data
  38608. * @param useBytes set to true if the offset is in bytes
  38609. */
  38610. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38611. if (useBytes === void 0) { useBytes = false; }
  38612. var vertexBuffer = this.getVertexBuffer(kind);
  38613. if (!vertexBuffer) {
  38614. return;
  38615. }
  38616. vertexBuffer.updateDirectly(data, offset, useBytes);
  38617. this.notifyUpdate(kind);
  38618. };
  38619. /**
  38620. * Update a specific vertex buffer
  38621. * This function will create a new buffer if the current one is not updatable
  38622. * @param kind defines the data kind (Position, normal, etc...)
  38623. * @param data defines the data to use
  38624. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38625. */
  38626. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38627. if (updateExtends === void 0) { updateExtends = false; }
  38628. var vertexBuffer = this.getVertexBuffer(kind);
  38629. if (!vertexBuffer) {
  38630. return;
  38631. }
  38632. vertexBuffer.update(data);
  38633. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38634. this._updateBoundingInfo(updateExtends, data);
  38635. }
  38636. this.notifyUpdate(kind);
  38637. };
  38638. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38639. if (updateExtends) {
  38640. this._updateExtend(data);
  38641. }
  38642. var meshes = this._meshes;
  38643. var numOfMeshes = meshes.length;
  38644. this._resetPointsArrayCache();
  38645. for (var index = 0; index < numOfMeshes; index++) {
  38646. var mesh = meshes[index];
  38647. if (updateExtends) {
  38648. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38649. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38650. var subMesh = mesh.subMeshes[subIndex];
  38651. subMesh.refreshBoundingInfo();
  38652. }
  38653. }
  38654. }
  38655. };
  38656. /** @hidden */
  38657. Geometry.prototype._bind = function (effect, indexToBind) {
  38658. if (!effect) {
  38659. return;
  38660. }
  38661. if (indexToBind === undefined) {
  38662. indexToBind = this._indexBuffer;
  38663. }
  38664. var vbs = this.getVertexBuffers();
  38665. if (!vbs) {
  38666. return;
  38667. }
  38668. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38669. this._engine.bindBuffers(vbs, indexToBind, effect);
  38670. return;
  38671. }
  38672. // Using VAO
  38673. if (!this._vertexArrayObjects[effect.key]) {
  38674. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38675. }
  38676. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38677. };
  38678. /**
  38679. * Gets total number of vertices
  38680. * @returns the total number of vertices
  38681. */
  38682. Geometry.prototype.getTotalVertices = function () {
  38683. if (!this.isReady()) {
  38684. return 0;
  38685. }
  38686. return this._totalVertices;
  38687. };
  38688. /**
  38689. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38690. * @param kind defines the data kind (Position, normal, etc...)
  38691. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38692. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38693. * @returns a float array containing vertex data
  38694. */
  38695. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38696. var vertexBuffer = this.getVertexBuffer(kind);
  38697. if (!vertexBuffer) {
  38698. return null;
  38699. }
  38700. var data = vertexBuffer.getData();
  38701. if (!data) {
  38702. return null;
  38703. }
  38704. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38705. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38706. var count = this._totalVertices * defaultStride;
  38707. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38708. var copy_1 = new Array(count);
  38709. vertexBuffer.forEach(count, function (value, index) {
  38710. copy_1[index] = value;
  38711. });
  38712. return copy_1;
  38713. }
  38714. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38715. if (data instanceof Array) {
  38716. var offset = vertexBuffer.byteOffset / 4;
  38717. return BABYLON.Tools.Slice(data, offset, offset + count);
  38718. }
  38719. else if (data instanceof ArrayBuffer) {
  38720. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38721. }
  38722. else {
  38723. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38724. }
  38725. }
  38726. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38727. return BABYLON.Tools.Slice(data);
  38728. }
  38729. return data;
  38730. };
  38731. /**
  38732. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38733. * @param kind defines the data kind (Position, normal, etc...)
  38734. * @returns true if the vertex buffer with the specified kind is updatable
  38735. */
  38736. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38737. var vb = this._vertexBuffers[kind];
  38738. if (!vb) {
  38739. return false;
  38740. }
  38741. return vb.isUpdatable();
  38742. };
  38743. /**
  38744. * Gets a specific vertex buffer
  38745. * @param kind defines the data kind (Position, normal, etc...)
  38746. * @returns a {BABYLON.VertexBuffer}
  38747. */
  38748. Geometry.prototype.getVertexBuffer = function (kind) {
  38749. if (!this.isReady()) {
  38750. return null;
  38751. }
  38752. return this._vertexBuffers[kind];
  38753. };
  38754. /**
  38755. * Returns all vertex buffers
  38756. * @return an object holding all vertex buffers indexed by kind
  38757. */
  38758. Geometry.prototype.getVertexBuffers = function () {
  38759. if (!this.isReady()) {
  38760. return null;
  38761. }
  38762. return this._vertexBuffers;
  38763. };
  38764. /**
  38765. * Gets a boolean indicating if specific vertex buffer is present
  38766. * @param kind defines the data kind (Position, normal, etc...)
  38767. * @returns true if data is present
  38768. */
  38769. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38770. if (!this._vertexBuffers) {
  38771. if (this._delayInfo) {
  38772. return this._delayInfo.indexOf(kind) !== -1;
  38773. }
  38774. return false;
  38775. }
  38776. return this._vertexBuffers[kind] !== undefined;
  38777. };
  38778. /**
  38779. * Gets a list of all attached data kinds (Position, normal, etc...)
  38780. * @returns a list of string containing all kinds
  38781. */
  38782. Geometry.prototype.getVerticesDataKinds = function () {
  38783. var result = [];
  38784. var kind;
  38785. if (!this._vertexBuffers && this._delayInfo) {
  38786. for (kind in this._delayInfo) {
  38787. result.push(kind);
  38788. }
  38789. }
  38790. else {
  38791. for (kind in this._vertexBuffers) {
  38792. result.push(kind);
  38793. }
  38794. }
  38795. return result;
  38796. };
  38797. /**
  38798. * Update index buffer
  38799. * @param indices defines the indices to store in the index buffer
  38800. * @param offset defines the offset in the target buffer where to store the data
  38801. */
  38802. Geometry.prototype.updateIndices = function (indices, offset) {
  38803. if (!this._indexBuffer) {
  38804. return;
  38805. }
  38806. if (!this._indexBufferIsUpdatable) {
  38807. this.setIndices(indices, null, true);
  38808. }
  38809. else {
  38810. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38811. }
  38812. };
  38813. /**
  38814. * Creates a new index buffer
  38815. * @param indices defines the indices to store in the index buffer
  38816. * @param totalVertices defines the total number of vertices (could be null)
  38817. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38818. */
  38819. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38820. if (totalVertices === void 0) { totalVertices = null; }
  38821. if (updatable === void 0) { updatable = false; }
  38822. if (this._indexBuffer) {
  38823. this._engine._releaseBuffer(this._indexBuffer);
  38824. }
  38825. this._disposeVertexArrayObjects();
  38826. this._indices = indices;
  38827. this._indexBufferIsUpdatable = updatable;
  38828. if (this._meshes.length !== 0 && this._indices) {
  38829. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38830. }
  38831. if (totalVertices != undefined) { // including null and undefined
  38832. this._totalVertices = totalVertices;
  38833. }
  38834. var meshes = this._meshes;
  38835. var numOfMeshes = meshes.length;
  38836. for (var index = 0; index < numOfMeshes; index++) {
  38837. meshes[index]._createGlobalSubMesh(true);
  38838. }
  38839. this.notifyUpdate();
  38840. };
  38841. /**
  38842. * Return the total number of indices
  38843. * @returns the total number of indices
  38844. */
  38845. Geometry.prototype.getTotalIndices = function () {
  38846. if (!this.isReady()) {
  38847. return 0;
  38848. }
  38849. return this._indices.length;
  38850. };
  38851. /**
  38852. * Gets the index buffer array
  38853. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38854. * @returns the index buffer array
  38855. */
  38856. Geometry.prototype.getIndices = function (copyWhenShared) {
  38857. if (!this.isReady()) {
  38858. return null;
  38859. }
  38860. var orig = this._indices;
  38861. if (!copyWhenShared || this._meshes.length === 1) {
  38862. return orig;
  38863. }
  38864. else {
  38865. var len = orig.length;
  38866. var copy = [];
  38867. for (var i = 0; i < len; i++) {
  38868. copy.push(orig[i]);
  38869. }
  38870. return copy;
  38871. }
  38872. };
  38873. /**
  38874. * Gets the index buffer
  38875. * @return the index buffer
  38876. */
  38877. Geometry.prototype.getIndexBuffer = function () {
  38878. if (!this.isReady()) {
  38879. return null;
  38880. }
  38881. return this._indexBuffer;
  38882. };
  38883. /** @hidden */
  38884. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38885. if (effect === void 0) { effect = null; }
  38886. if (!effect || !this._vertexArrayObjects) {
  38887. return;
  38888. }
  38889. if (this._vertexArrayObjects[effect.key]) {
  38890. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38891. delete this._vertexArrayObjects[effect.key];
  38892. }
  38893. };
  38894. /**
  38895. * Release the associated resources for a specific mesh
  38896. * @param mesh defines the source mesh
  38897. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38898. */
  38899. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38900. var meshes = this._meshes;
  38901. var index = meshes.indexOf(mesh);
  38902. if (index === -1) {
  38903. return;
  38904. }
  38905. meshes.splice(index, 1);
  38906. mesh._geometry = null;
  38907. if (meshes.length === 0 && shouldDispose) {
  38908. this.dispose();
  38909. }
  38910. };
  38911. /**
  38912. * Apply current geometry to a given mesh
  38913. * @param mesh defines the mesh to apply geometry to
  38914. */
  38915. Geometry.prototype.applyToMesh = function (mesh) {
  38916. if (mesh._geometry === this) {
  38917. return;
  38918. }
  38919. var previousGeometry = mesh._geometry;
  38920. if (previousGeometry) {
  38921. previousGeometry.releaseForMesh(mesh);
  38922. }
  38923. var meshes = this._meshes;
  38924. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38925. mesh._geometry = this;
  38926. this._scene.pushGeometry(this);
  38927. meshes.push(mesh);
  38928. if (this.isReady()) {
  38929. this._applyToMesh(mesh);
  38930. }
  38931. else {
  38932. mesh._boundingInfo = this._boundingInfo;
  38933. }
  38934. };
  38935. Geometry.prototype._updateExtend = function (data) {
  38936. if (data === void 0) { data = null; }
  38937. if (!data) {
  38938. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38939. }
  38940. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38941. };
  38942. Geometry.prototype._applyToMesh = function (mesh) {
  38943. var numOfMeshes = this._meshes.length;
  38944. // vertexBuffers
  38945. for (var kind in this._vertexBuffers) {
  38946. if (numOfMeshes === 1) {
  38947. this._vertexBuffers[kind].create();
  38948. }
  38949. var buffer = this._vertexBuffers[kind].getBuffer();
  38950. if (buffer)
  38951. buffer.references = numOfMeshes;
  38952. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38953. if (!this._extend) {
  38954. this._updateExtend();
  38955. }
  38956. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38957. mesh._createGlobalSubMesh(false);
  38958. //bounding info was just created again, world matrix should be applied again.
  38959. mesh._updateBoundingInfo();
  38960. }
  38961. }
  38962. // indexBuffer
  38963. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38964. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38965. }
  38966. if (this._indexBuffer) {
  38967. this._indexBuffer.references = numOfMeshes;
  38968. }
  38969. };
  38970. Geometry.prototype.notifyUpdate = function (kind) {
  38971. if (this.onGeometryUpdated) {
  38972. this.onGeometryUpdated(this, kind);
  38973. }
  38974. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38975. var mesh = _a[_i];
  38976. mesh._markSubMeshesAsAttributesDirty();
  38977. }
  38978. };
  38979. /**
  38980. * Load the geometry if it was flagged as delay loaded
  38981. * @param scene defines the hosting scene
  38982. * @param onLoaded defines a callback called when the geometry is loaded
  38983. */
  38984. Geometry.prototype.load = function (scene, onLoaded) {
  38985. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38986. return;
  38987. }
  38988. if (this.isReady()) {
  38989. if (onLoaded) {
  38990. onLoaded();
  38991. }
  38992. return;
  38993. }
  38994. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38995. this._queueLoad(scene, onLoaded);
  38996. };
  38997. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38998. var _this = this;
  38999. if (!this.delayLoadingFile) {
  39000. return;
  39001. }
  39002. scene._addPendingData(this);
  39003. scene._loadFile(this.delayLoadingFile, function (data) {
  39004. if (!_this._delayLoadingFunction) {
  39005. return;
  39006. }
  39007. _this._delayLoadingFunction(JSON.parse(data), _this);
  39008. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39009. _this._delayInfo = [];
  39010. scene._removePendingData(_this);
  39011. var meshes = _this._meshes;
  39012. var numOfMeshes = meshes.length;
  39013. for (var index = 0; index < numOfMeshes; index++) {
  39014. _this._applyToMesh(meshes[index]);
  39015. }
  39016. if (onLoaded) {
  39017. onLoaded();
  39018. }
  39019. }, undefined, true);
  39020. };
  39021. /**
  39022. * Invert the geometry to move from a right handed system to a left handed one.
  39023. */
  39024. Geometry.prototype.toLeftHanded = function () {
  39025. // Flip faces
  39026. var tIndices = this.getIndices(false);
  39027. if (tIndices != null && tIndices.length > 0) {
  39028. for (var i = 0; i < tIndices.length; i += 3) {
  39029. var tTemp = tIndices[i + 0];
  39030. tIndices[i + 0] = tIndices[i + 2];
  39031. tIndices[i + 2] = tTemp;
  39032. }
  39033. this.setIndices(tIndices);
  39034. }
  39035. // Negate position.z
  39036. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39037. if (tPositions != null && tPositions.length > 0) {
  39038. for (var i = 0; i < tPositions.length; i += 3) {
  39039. tPositions[i + 2] = -tPositions[i + 2];
  39040. }
  39041. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39042. }
  39043. // Negate normal.z
  39044. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39045. if (tNormals != null && tNormals.length > 0) {
  39046. for (var i = 0; i < tNormals.length; i += 3) {
  39047. tNormals[i + 2] = -tNormals[i + 2];
  39048. }
  39049. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39050. }
  39051. };
  39052. // Cache
  39053. /** @hidden */
  39054. Geometry.prototype._resetPointsArrayCache = function () {
  39055. this._positions = null;
  39056. };
  39057. /** @hidden */
  39058. Geometry.prototype._generatePointsArray = function () {
  39059. if (this._positions)
  39060. return true;
  39061. this._positions = [];
  39062. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39063. if (!data) {
  39064. return false;
  39065. }
  39066. for (var index = 0; index < data.length; index += 3) {
  39067. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39068. }
  39069. return true;
  39070. };
  39071. /**
  39072. * Gets a value indicating if the geometry is disposed
  39073. * @returns true if the geometry was disposed
  39074. */
  39075. Geometry.prototype.isDisposed = function () {
  39076. return this._isDisposed;
  39077. };
  39078. Geometry.prototype._disposeVertexArrayObjects = function () {
  39079. if (this._vertexArrayObjects) {
  39080. for (var kind in this._vertexArrayObjects) {
  39081. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39082. }
  39083. this._vertexArrayObjects = {};
  39084. }
  39085. };
  39086. /**
  39087. * Free all associated resources
  39088. */
  39089. Geometry.prototype.dispose = function () {
  39090. var meshes = this._meshes;
  39091. var numOfMeshes = meshes.length;
  39092. var index;
  39093. for (index = 0; index < numOfMeshes; index++) {
  39094. this.releaseForMesh(meshes[index]);
  39095. }
  39096. this._meshes = [];
  39097. this._disposeVertexArrayObjects();
  39098. for (var kind in this._vertexBuffers) {
  39099. this._vertexBuffers[kind].dispose();
  39100. }
  39101. this._vertexBuffers = {};
  39102. this._totalVertices = 0;
  39103. if (this._indexBuffer) {
  39104. this._engine._releaseBuffer(this._indexBuffer);
  39105. }
  39106. this._indexBuffer = null;
  39107. this._indices = [];
  39108. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39109. this.delayLoadingFile = null;
  39110. this._delayLoadingFunction = null;
  39111. this._delayInfo = [];
  39112. this._boundingInfo = null;
  39113. this._scene.removeGeometry(this);
  39114. this._isDisposed = true;
  39115. };
  39116. /**
  39117. * Clone the current geometry into a new geometry
  39118. * @param id defines the unique ID of the new geometry
  39119. * @returns a new geometry object
  39120. */
  39121. Geometry.prototype.copy = function (id) {
  39122. var vertexData = new BABYLON.VertexData();
  39123. vertexData.indices = [];
  39124. var indices = this.getIndices();
  39125. if (indices) {
  39126. for (var index = 0; index < indices.length; index++) {
  39127. vertexData.indices.push(indices[index]);
  39128. }
  39129. }
  39130. var updatable = false;
  39131. var stopChecking = false;
  39132. var kind;
  39133. for (kind in this._vertexBuffers) {
  39134. // using slice() to make a copy of the array and not just reference it
  39135. var data = this.getVerticesData(kind);
  39136. if (data instanceof Float32Array) {
  39137. vertexData.set(new Float32Array(data), kind);
  39138. }
  39139. else {
  39140. vertexData.set(data.slice(0), kind);
  39141. }
  39142. if (!stopChecking) {
  39143. var vb = this.getVertexBuffer(kind);
  39144. if (vb) {
  39145. updatable = vb.isUpdatable();
  39146. stopChecking = !updatable;
  39147. }
  39148. }
  39149. }
  39150. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39151. geometry.delayLoadState = this.delayLoadState;
  39152. geometry.delayLoadingFile = this.delayLoadingFile;
  39153. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39154. for (kind in this._delayInfo) {
  39155. geometry._delayInfo = geometry._delayInfo || [];
  39156. geometry._delayInfo.push(kind);
  39157. }
  39158. // Bounding info
  39159. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39160. return geometry;
  39161. };
  39162. /**
  39163. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39164. * @return a JSON representation of the current geometry data (without the vertices data)
  39165. */
  39166. Geometry.prototype.serialize = function () {
  39167. var serializationObject = {};
  39168. serializationObject.id = this.id;
  39169. serializationObject.updatable = this._updatable;
  39170. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39171. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39172. }
  39173. return serializationObject;
  39174. };
  39175. Geometry.prototype.toNumberArray = function (origin) {
  39176. if (Array.isArray(origin)) {
  39177. return origin;
  39178. }
  39179. else {
  39180. return Array.prototype.slice.call(origin);
  39181. }
  39182. };
  39183. /**
  39184. * Serialize all vertices data into a JSON oject
  39185. * @returns a JSON representation of the current geometry data
  39186. */
  39187. Geometry.prototype.serializeVerticeData = function () {
  39188. var serializationObject = this.serialize();
  39189. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39190. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39191. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39192. serializationObject.positions._updatable = true;
  39193. }
  39194. }
  39195. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39196. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39197. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39198. serializationObject.normals._updatable = true;
  39199. }
  39200. }
  39201. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39202. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39203. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39204. serializationObject.tangets._updatable = true;
  39205. }
  39206. }
  39207. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39208. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39209. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39210. serializationObject.uvs._updatable = true;
  39211. }
  39212. }
  39213. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39214. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39215. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39216. serializationObject.uv2s._updatable = true;
  39217. }
  39218. }
  39219. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39220. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39221. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39222. serializationObject.uv3s._updatable = true;
  39223. }
  39224. }
  39225. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39226. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39227. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39228. serializationObject.uv4s._updatable = true;
  39229. }
  39230. }
  39231. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39232. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39233. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39234. serializationObject.uv5s._updatable = true;
  39235. }
  39236. }
  39237. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39238. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39239. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39240. serializationObject.uv6s._updatable = true;
  39241. }
  39242. }
  39243. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39244. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39245. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39246. serializationObject.colors._updatable = true;
  39247. }
  39248. }
  39249. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39250. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39251. serializationObject.matricesIndices._isExpanded = true;
  39252. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39253. serializationObject.matricesIndices._updatable = true;
  39254. }
  39255. }
  39256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39257. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39258. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39259. serializationObject.matricesWeights._updatable = true;
  39260. }
  39261. }
  39262. serializationObject.indices = this.toNumberArray(this.getIndices());
  39263. return serializationObject;
  39264. };
  39265. // Statics
  39266. /**
  39267. * Extracts a clone of a mesh geometry
  39268. * @param mesh defines the source mesh
  39269. * @param id defines the unique ID of the new geometry object
  39270. * @returns the new geometry object
  39271. */
  39272. Geometry.ExtractFromMesh = function (mesh, id) {
  39273. var geometry = mesh._geometry;
  39274. if (!geometry) {
  39275. return null;
  39276. }
  39277. return geometry.copy(id);
  39278. };
  39279. /**
  39280. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39281. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39282. * Be aware Math.random() could cause collisions, but:
  39283. * "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"
  39284. * @returns a string containing a new GUID
  39285. */
  39286. Geometry.RandomId = function () {
  39287. return BABYLON.Tools.RandomId();
  39288. };
  39289. /** @hidden */
  39290. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39291. var scene = mesh.getScene();
  39292. // Geometry
  39293. var geometryId = parsedGeometry.geometryId;
  39294. if (geometryId) {
  39295. var geometry = scene.getGeometryByID(geometryId);
  39296. if (geometry) {
  39297. geometry.applyToMesh(mesh);
  39298. }
  39299. }
  39300. else if (parsedGeometry instanceof ArrayBuffer) {
  39301. var binaryInfo = mesh._binaryInfo;
  39302. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39303. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39304. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39305. }
  39306. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39307. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39308. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39309. }
  39310. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39311. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39312. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39313. }
  39314. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39315. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39316. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39317. }
  39318. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39319. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39320. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39321. }
  39322. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39323. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39324. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39325. }
  39326. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39327. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39328. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39329. }
  39330. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39331. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39332. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39333. }
  39334. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39335. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39336. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39337. }
  39338. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39339. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39340. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39341. }
  39342. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39343. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39344. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39345. }
  39346. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39347. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39348. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39349. }
  39350. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39351. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39352. mesh.setIndices(indicesData, null);
  39353. }
  39354. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39355. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39356. mesh.subMeshes = [];
  39357. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39358. var materialIndex = subMeshesData[(i * 5) + 0];
  39359. var verticesStart = subMeshesData[(i * 5) + 1];
  39360. var verticesCount = subMeshesData[(i * 5) + 2];
  39361. var indexStart = subMeshesData[(i * 5) + 3];
  39362. var indexCount = subMeshesData[(i * 5) + 4];
  39363. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39364. }
  39365. }
  39366. }
  39367. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39368. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39369. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39370. if (parsedGeometry.tangents) {
  39371. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39372. }
  39373. if (parsedGeometry.uvs) {
  39374. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39375. }
  39376. if (parsedGeometry.uvs2) {
  39377. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39378. }
  39379. if (parsedGeometry.uvs3) {
  39380. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39381. }
  39382. if (parsedGeometry.uvs4) {
  39383. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39384. }
  39385. if (parsedGeometry.uvs5) {
  39386. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39387. }
  39388. if (parsedGeometry.uvs6) {
  39389. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39390. }
  39391. if (parsedGeometry.colors) {
  39392. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39393. }
  39394. if (parsedGeometry.matricesIndices) {
  39395. if (!parsedGeometry.matricesIndices._isExpanded) {
  39396. var floatIndices = [];
  39397. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39398. var matricesIndex = parsedGeometry.matricesIndices[i];
  39399. floatIndices.push(matricesIndex & 0x000000FF);
  39400. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39401. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39402. floatIndices.push(matricesIndex >> 24);
  39403. }
  39404. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39405. }
  39406. else {
  39407. delete parsedGeometry.matricesIndices._isExpanded;
  39408. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39409. }
  39410. }
  39411. if (parsedGeometry.matricesIndicesExtra) {
  39412. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39413. var floatIndices = [];
  39414. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39415. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39416. floatIndices.push(matricesIndex & 0x000000FF);
  39417. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39418. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39419. floatIndices.push(matricesIndex >> 24);
  39420. }
  39421. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39422. }
  39423. else {
  39424. delete parsedGeometry.matricesIndices._isExpanded;
  39425. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39426. }
  39427. }
  39428. if (parsedGeometry.matricesWeights) {
  39429. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39431. }
  39432. if (parsedGeometry.matricesWeightsExtra) {
  39433. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39434. }
  39435. mesh.setIndices(parsedGeometry.indices, null);
  39436. }
  39437. // SubMeshes
  39438. if (parsedGeometry.subMeshes) {
  39439. mesh.subMeshes = [];
  39440. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39441. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39442. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39443. }
  39444. }
  39445. // Flat shading
  39446. if (mesh._shouldGenerateFlatShading) {
  39447. mesh.convertToFlatShadedMesh();
  39448. delete mesh._shouldGenerateFlatShading;
  39449. }
  39450. // Update
  39451. mesh.computeWorldMatrix(true);
  39452. // Octree
  39453. var sceneOctree = scene.selectionOctree;
  39454. if (sceneOctree !== undefined && sceneOctree !== null) {
  39455. sceneOctree.addMesh(mesh);
  39456. }
  39457. };
  39458. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39459. var epsilon = 1e-3;
  39460. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39461. return;
  39462. }
  39463. var noInfluenceBoneIndex = 0.0;
  39464. if (parsedGeometry.skeletonId > -1) {
  39465. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39466. if (!skeleton) {
  39467. return;
  39468. }
  39469. noInfluenceBoneIndex = skeleton.bones.length;
  39470. }
  39471. else {
  39472. return;
  39473. }
  39474. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39475. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39476. var matricesWeights = parsedGeometry.matricesWeights;
  39477. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39478. var influencers = parsedGeometry.numBoneInfluencer;
  39479. var size = matricesWeights.length;
  39480. for (var i = 0; i < size; i += 4) {
  39481. var weight = 0.0;
  39482. var firstZeroWeight = -1;
  39483. for (var j = 0; j < 4; j++) {
  39484. var w = matricesWeights[i + j];
  39485. weight += w;
  39486. if (w < epsilon && firstZeroWeight < 0) {
  39487. firstZeroWeight = j;
  39488. }
  39489. }
  39490. if (matricesWeightsExtra) {
  39491. for (var j = 0; j < 4; j++) {
  39492. var w = matricesWeightsExtra[i + j];
  39493. weight += w;
  39494. if (w < epsilon && firstZeroWeight < 0) {
  39495. firstZeroWeight = j + 4;
  39496. }
  39497. }
  39498. }
  39499. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39500. firstZeroWeight = influencers - 1;
  39501. }
  39502. if (weight > epsilon) {
  39503. var mweight = 1.0 / weight;
  39504. for (var j = 0; j < 4; j++) {
  39505. matricesWeights[i + j] *= mweight;
  39506. }
  39507. if (matricesWeightsExtra) {
  39508. for (var j = 0; j < 4; j++) {
  39509. matricesWeightsExtra[i + j] *= mweight;
  39510. }
  39511. }
  39512. }
  39513. else {
  39514. if (firstZeroWeight >= 4) {
  39515. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39516. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39517. }
  39518. else {
  39519. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39520. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39521. }
  39522. }
  39523. }
  39524. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39525. if (parsedGeometry.matricesWeightsExtra) {
  39526. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39527. }
  39528. };
  39529. /**
  39530. * Create a new geometry from persisted data (Using .babylon file format)
  39531. * @param parsedVertexData defines the persisted data
  39532. * @param scene defines the hosting scene
  39533. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39534. * @returns the new geometry object
  39535. */
  39536. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39537. if (scene.getGeometryByID(parsedVertexData.id)) {
  39538. return null; // null since geometry could be something else than a box...
  39539. }
  39540. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39541. if (BABYLON.Tags) {
  39542. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39543. }
  39544. if (parsedVertexData.delayLoadingFile) {
  39545. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39546. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39547. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39548. geometry._delayInfo = [];
  39549. if (parsedVertexData.hasUVs) {
  39550. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39551. }
  39552. if (parsedVertexData.hasUVs2) {
  39553. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39554. }
  39555. if (parsedVertexData.hasUVs3) {
  39556. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39557. }
  39558. if (parsedVertexData.hasUVs4) {
  39559. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39560. }
  39561. if (parsedVertexData.hasUVs5) {
  39562. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39563. }
  39564. if (parsedVertexData.hasUVs6) {
  39565. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39566. }
  39567. if (parsedVertexData.hasColors) {
  39568. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39569. }
  39570. if (parsedVertexData.hasMatricesIndices) {
  39571. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39572. }
  39573. if (parsedVertexData.hasMatricesWeights) {
  39574. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39575. }
  39576. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39577. }
  39578. else {
  39579. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39580. }
  39581. scene.pushGeometry(geometry, true);
  39582. return geometry;
  39583. };
  39584. return Geometry;
  39585. }());
  39586. BABYLON.Geometry = Geometry;
  39587. // Primitives
  39588. /// Abstract class
  39589. /**
  39590. * Abstract class used to provide common services for all typed geometries
  39591. * @hidden
  39592. */
  39593. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39594. __extends(_PrimitiveGeometry, _super);
  39595. /**
  39596. * Creates a new typed geometry
  39597. * @param id defines the unique ID of the geometry
  39598. * @param scene defines the hosting scene
  39599. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39600. * @param mesh defines the hosting mesh (can be null)
  39601. */
  39602. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39603. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39604. if (mesh === void 0) { mesh = null; }
  39605. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39606. _this._canBeRegenerated = _canBeRegenerated;
  39607. _this._beingRegenerated = true;
  39608. _this.regenerate();
  39609. _this._beingRegenerated = false;
  39610. return _this;
  39611. }
  39612. /**
  39613. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39614. * @returns true if the geometry can be regenerated
  39615. */
  39616. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39617. return this._canBeRegenerated;
  39618. };
  39619. /**
  39620. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39621. */
  39622. _PrimitiveGeometry.prototype.regenerate = function () {
  39623. if (!this._canBeRegenerated) {
  39624. return;
  39625. }
  39626. this._beingRegenerated = true;
  39627. this.setAllVerticesData(this._regenerateVertexData(), false);
  39628. this._beingRegenerated = false;
  39629. };
  39630. /**
  39631. * Clone the geometry
  39632. * @param id defines the unique ID of the new geometry
  39633. * @returns the new geometry
  39634. */
  39635. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39636. return _super.prototype.copy.call(this, id);
  39637. };
  39638. // overrides
  39639. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39640. if (!this._beingRegenerated) {
  39641. return;
  39642. }
  39643. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39644. };
  39645. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39646. if (!this._beingRegenerated) {
  39647. return;
  39648. }
  39649. _super.prototype.setVerticesData.call(this, kind, data, false);
  39650. };
  39651. // to override
  39652. /** @hidden */
  39653. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39654. throw new Error("Abstract method");
  39655. };
  39656. _PrimitiveGeometry.prototype.copy = function (id) {
  39657. throw new Error("Must be overriden in sub-classes.");
  39658. };
  39659. _PrimitiveGeometry.prototype.serialize = function () {
  39660. var serializationObject = _super.prototype.serialize.call(this);
  39661. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39662. return serializationObject;
  39663. };
  39664. return _PrimitiveGeometry;
  39665. }(Geometry));
  39666. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39667. /**
  39668. * Creates a ribbon geometry
  39669. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39670. */
  39671. var RibbonGeometry = /** @class */ (function (_super) {
  39672. __extends(RibbonGeometry, _super);
  39673. /**
  39674. * Creates a ribbon geometry
  39675. * @param id defines the unique ID of the geometry
  39676. * @param scene defines the hosting scene
  39677. * @param pathArray defines the array of paths to use
  39678. * @param closeArray defines if the last path and the first path must be joined
  39679. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39680. * @param offset defines the offset between points
  39681. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39682. * @param mesh defines the hosting mesh (can be null)
  39683. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39684. */
  39685. function RibbonGeometry(id, scene,
  39686. /**
  39687. * Defines the array of paths to use
  39688. */
  39689. pathArray,
  39690. /**
  39691. * Defines if the last and first points of each path in your pathArray must be joined
  39692. */
  39693. closeArray,
  39694. /**
  39695. * Defines if the last and first points of each path in your pathArray must be joined
  39696. */
  39697. closePath,
  39698. /**
  39699. * Defines the offset between points
  39700. */
  39701. offset, canBeRegenerated, mesh,
  39702. /**
  39703. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39704. */
  39705. side) {
  39706. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39707. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39708. _this.pathArray = pathArray;
  39709. _this.closeArray = closeArray;
  39710. _this.closePath = closePath;
  39711. _this.offset = offset;
  39712. _this.side = side;
  39713. return _this;
  39714. }
  39715. /** @hidden */
  39716. RibbonGeometry.prototype._regenerateVertexData = function () {
  39717. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39718. };
  39719. RibbonGeometry.prototype.copy = function (id) {
  39720. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39721. };
  39722. return RibbonGeometry;
  39723. }(_PrimitiveGeometry));
  39724. BABYLON.RibbonGeometry = RibbonGeometry;
  39725. /**
  39726. * Creates a box geometry
  39727. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39728. */
  39729. var BoxGeometry = /** @class */ (function (_super) {
  39730. __extends(BoxGeometry, _super);
  39731. /**
  39732. * Creates a box geometry
  39733. * @param id defines the unique ID of the geometry
  39734. * @param scene defines the hosting scene
  39735. * @param size defines the zise of the box (width, height and depth are the same)
  39736. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39737. * @param mesh defines the hosting mesh (can be null)
  39738. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39739. */
  39740. function BoxGeometry(id, scene,
  39741. /**
  39742. * Defines the zise of the box (width, height and depth are the same)
  39743. */
  39744. size, canBeRegenerated, mesh,
  39745. /**
  39746. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39747. */
  39748. side) {
  39749. if (mesh === void 0) { mesh = null; }
  39750. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39751. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39752. _this.size = size;
  39753. _this.side = side;
  39754. return _this;
  39755. }
  39756. BoxGeometry.prototype._regenerateVertexData = function () {
  39757. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39758. };
  39759. BoxGeometry.prototype.copy = function (id) {
  39760. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39761. };
  39762. BoxGeometry.prototype.serialize = function () {
  39763. var serializationObject = _super.prototype.serialize.call(this);
  39764. serializationObject.size = this.size;
  39765. return serializationObject;
  39766. };
  39767. BoxGeometry.Parse = function (parsedBox, scene) {
  39768. if (scene.getGeometryByID(parsedBox.id)) {
  39769. return null; // null since geometry could be something else than a box...
  39770. }
  39771. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39772. if (BABYLON.Tags) {
  39773. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39774. }
  39775. scene.pushGeometry(box, true);
  39776. return box;
  39777. };
  39778. return BoxGeometry;
  39779. }(_PrimitiveGeometry));
  39780. BABYLON.BoxGeometry = BoxGeometry;
  39781. /**
  39782. * Creates a sphere geometry
  39783. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39784. */
  39785. var SphereGeometry = /** @class */ (function (_super) {
  39786. __extends(SphereGeometry, _super);
  39787. /**
  39788. * Create a new sphere geometry
  39789. * @param id defines the unique ID of the geometry
  39790. * @param scene defines the hosting scene
  39791. * @param segments defines the number of segments to use to create the sphere
  39792. * @param diameter defines the diameter of the sphere
  39793. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39794. * @param mesh defines the hosting mesh (can be null)
  39795. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39796. */
  39797. function SphereGeometry(id, scene,
  39798. /**
  39799. * Defines the number of segments to use to create the sphere
  39800. */
  39801. segments,
  39802. /**
  39803. * Defines the diameter of the sphere
  39804. */
  39805. diameter, canBeRegenerated, mesh,
  39806. /**
  39807. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39808. */
  39809. side) {
  39810. if (mesh === void 0) { mesh = null; }
  39811. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39812. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39813. _this.segments = segments;
  39814. _this.diameter = diameter;
  39815. _this.side = side;
  39816. return _this;
  39817. }
  39818. SphereGeometry.prototype._regenerateVertexData = function () {
  39819. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39820. };
  39821. SphereGeometry.prototype.copy = function (id) {
  39822. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39823. };
  39824. SphereGeometry.prototype.serialize = function () {
  39825. var serializationObject = _super.prototype.serialize.call(this);
  39826. serializationObject.segments = this.segments;
  39827. serializationObject.diameter = this.diameter;
  39828. return serializationObject;
  39829. };
  39830. SphereGeometry.Parse = function (parsedSphere, scene) {
  39831. if (scene.getGeometryByID(parsedSphere.id)) {
  39832. return null; // null since geometry could be something else than a sphere...
  39833. }
  39834. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39835. if (BABYLON.Tags) {
  39836. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39837. }
  39838. scene.pushGeometry(sphere, true);
  39839. return sphere;
  39840. };
  39841. return SphereGeometry;
  39842. }(_PrimitiveGeometry));
  39843. BABYLON.SphereGeometry = SphereGeometry;
  39844. /**
  39845. * Creates a disc geometry
  39846. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39847. */
  39848. var DiscGeometry = /** @class */ (function (_super) {
  39849. __extends(DiscGeometry, _super);
  39850. /**
  39851. * Creates a new disc geometry
  39852. * @param id defines the unique ID of the geometry
  39853. * @param scene defines the hosting scene
  39854. * @param radius defines the radius of the disc
  39855. * @param tessellation defines the tesselation factor to apply to the disc
  39856. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39857. * @param mesh defines the hosting mesh (can be null)
  39858. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39859. */
  39860. function DiscGeometry(id, scene,
  39861. /**
  39862. * Defines the radius of the disc
  39863. */
  39864. radius,
  39865. /**
  39866. * Defines the tesselation factor to apply to the disc
  39867. */
  39868. tessellation, canBeRegenerated, mesh,
  39869. /**
  39870. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39871. */
  39872. side) {
  39873. if (mesh === void 0) { mesh = null; }
  39874. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39875. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39876. _this.radius = radius;
  39877. _this.tessellation = tessellation;
  39878. _this.side = side;
  39879. return _this;
  39880. }
  39881. DiscGeometry.prototype._regenerateVertexData = function () {
  39882. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39883. };
  39884. DiscGeometry.prototype.copy = function (id) {
  39885. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39886. };
  39887. return DiscGeometry;
  39888. }(_PrimitiveGeometry));
  39889. BABYLON.DiscGeometry = DiscGeometry;
  39890. /**
  39891. * Creates a new cylinder geometry
  39892. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39893. */
  39894. var CylinderGeometry = /** @class */ (function (_super) {
  39895. __extends(CylinderGeometry, _super);
  39896. /**
  39897. * Creates a new cylinder geometry
  39898. * @param id defines the unique ID of the geometry
  39899. * @param scene defines the hosting scene
  39900. * @param height defines the height of the cylinder
  39901. * @param diameterTop defines the diameter of the cylinder's top cap
  39902. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39903. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39904. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39905. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39906. * @param mesh defines the hosting mesh (can be null)
  39907. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39908. */
  39909. function CylinderGeometry(id, scene,
  39910. /**
  39911. * Defines the height of the cylinder
  39912. */
  39913. height,
  39914. /**
  39915. * Defines the diameter of the cylinder's top cap
  39916. */
  39917. diameterTop,
  39918. /**
  39919. * Defines the diameter of the cylinder's bottom cap
  39920. */
  39921. diameterBottom,
  39922. /**
  39923. * Defines the tessellation factor to apply to the cylinder
  39924. */
  39925. tessellation,
  39926. /**
  39927. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39928. */
  39929. subdivisions, canBeRegenerated, mesh,
  39930. /**
  39931. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39932. */
  39933. side) {
  39934. if (subdivisions === void 0) { subdivisions = 1; }
  39935. if (mesh === void 0) { mesh = null; }
  39936. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39937. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39938. _this.height = height;
  39939. _this.diameterTop = diameterTop;
  39940. _this.diameterBottom = diameterBottom;
  39941. _this.tessellation = tessellation;
  39942. _this.subdivisions = subdivisions;
  39943. _this.side = side;
  39944. return _this;
  39945. }
  39946. CylinderGeometry.prototype._regenerateVertexData = function () {
  39947. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39948. };
  39949. CylinderGeometry.prototype.copy = function (id) {
  39950. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39951. };
  39952. CylinderGeometry.prototype.serialize = function () {
  39953. var serializationObject = _super.prototype.serialize.call(this);
  39954. serializationObject.height = this.height;
  39955. serializationObject.diameterTop = this.diameterTop;
  39956. serializationObject.diameterBottom = this.diameterBottom;
  39957. serializationObject.tessellation = this.tessellation;
  39958. return serializationObject;
  39959. };
  39960. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39961. if (scene.getGeometryByID(parsedCylinder.id)) {
  39962. return null; // null since geometry could be something else than a cylinder...
  39963. }
  39964. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39965. if (BABYLON.Tags) {
  39966. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39967. }
  39968. scene.pushGeometry(cylinder, true);
  39969. return cylinder;
  39970. };
  39971. return CylinderGeometry;
  39972. }(_PrimitiveGeometry));
  39973. BABYLON.CylinderGeometry = CylinderGeometry;
  39974. /**
  39975. * Creates a new torus geometry
  39976. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39977. */
  39978. var TorusGeometry = /** @class */ (function (_super) {
  39979. __extends(TorusGeometry, _super);
  39980. /**
  39981. * Creates a new torus geometry
  39982. * @param id defines the unique ID of the geometry
  39983. * @param scene defines the hosting scene
  39984. * @param diameter defines the diameter of the torus
  39985. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39986. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39987. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39988. * @param mesh defines the hosting mesh (can be null)
  39989. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39990. */
  39991. function TorusGeometry(id, scene,
  39992. /**
  39993. * Defines the diameter of the torus
  39994. */
  39995. diameter,
  39996. /**
  39997. * Defines the thickness of the torus (ie. internal diameter)
  39998. */
  39999. thickness,
  40000. /**
  40001. * Defines the tesselation factor to apply to the torus
  40002. */
  40003. tessellation, canBeRegenerated, mesh,
  40004. /**
  40005. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40006. */
  40007. side) {
  40008. if (mesh === void 0) { mesh = null; }
  40009. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40010. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40011. _this.diameter = diameter;
  40012. _this.thickness = thickness;
  40013. _this.tessellation = tessellation;
  40014. _this.side = side;
  40015. return _this;
  40016. }
  40017. TorusGeometry.prototype._regenerateVertexData = function () {
  40018. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40019. };
  40020. TorusGeometry.prototype.copy = function (id) {
  40021. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40022. };
  40023. TorusGeometry.prototype.serialize = function () {
  40024. var serializationObject = _super.prototype.serialize.call(this);
  40025. serializationObject.diameter = this.diameter;
  40026. serializationObject.thickness = this.thickness;
  40027. serializationObject.tessellation = this.tessellation;
  40028. return serializationObject;
  40029. };
  40030. TorusGeometry.Parse = function (parsedTorus, scene) {
  40031. if (scene.getGeometryByID(parsedTorus.id)) {
  40032. return null; // null since geometry could be something else than a torus...
  40033. }
  40034. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40035. if (BABYLON.Tags) {
  40036. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40037. }
  40038. scene.pushGeometry(torus, true);
  40039. return torus;
  40040. };
  40041. return TorusGeometry;
  40042. }(_PrimitiveGeometry));
  40043. BABYLON.TorusGeometry = TorusGeometry;
  40044. /**
  40045. * Creates a new ground geometry
  40046. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40047. */
  40048. var GroundGeometry = /** @class */ (function (_super) {
  40049. __extends(GroundGeometry, _super);
  40050. /**
  40051. * Creates a new ground geometry
  40052. * @param id defines the unique ID of the geometry
  40053. * @param scene defines the hosting scene
  40054. * @param width defines the width of the ground
  40055. * @param height defines the height of the ground
  40056. * @param subdivisions defines the subdivisions to apply to the ground
  40057. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40058. * @param mesh defines the hosting mesh (can be null)
  40059. */
  40060. function GroundGeometry(id, scene,
  40061. /**
  40062. * Defines the width of the ground
  40063. */
  40064. width,
  40065. /**
  40066. * Defines the height of the ground
  40067. */
  40068. height,
  40069. /**
  40070. * Defines the subdivisions to apply to the ground
  40071. */
  40072. subdivisions, canBeRegenerated, mesh) {
  40073. if (mesh === void 0) { mesh = null; }
  40074. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40075. _this.width = width;
  40076. _this.height = height;
  40077. _this.subdivisions = subdivisions;
  40078. return _this;
  40079. }
  40080. GroundGeometry.prototype._regenerateVertexData = function () {
  40081. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40082. };
  40083. GroundGeometry.prototype.copy = function (id) {
  40084. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40085. };
  40086. GroundGeometry.prototype.serialize = function () {
  40087. var serializationObject = _super.prototype.serialize.call(this);
  40088. serializationObject.width = this.width;
  40089. serializationObject.height = this.height;
  40090. serializationObject.subdivisions = this.subdivisions;
  40091. return serializationObject;
  40092. };
  40093. GroundGeometry.Parse = function (parsedGround, scene) {
  40094. if (scene.getGeometryByID(parsedGround.id)) {
  40095. return null; // null since geometry could be something else than a ground...
  40096. }
  40097. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40098. if (BABYLON.Tags) {
  40099. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40100. }
  40101. scene.pushGeometry(ground, true);
  40102. return ground;
  40103. };
  40104. return GroundGeometry;
  40105. }(_PrimitiveGeometry));
  40106. BABYLON.GroundGeometry = GroundGeometry;
  40107. /**
  40108. * Creates a tiled ground geometry
  40109. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40110. */
  40111. var TiledGroundGeometry = /** @class */ (function (_super) {
  40112. __extends(TiledGroundGeometry, _super);
  40113. /**
  40114. * Creates a tiled ground geometry
  40115. * @param id defines the unique ID of the geometry
  40116. * @param scene defines the hosting scene
  40117. * @param xmin defines the minimum value on X axis
  40118. * @param zmin defines the minimum value on Z axis
  40119. * @param xmax defines the maximum value on X axis
  40120. * @param zmax defines the maximum value on Z axis
  40121. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40122. * @param precision defines the precision to use when computing the tiles
  40123. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40124. * @param mesh defines the hosting mesh (can be null)
  40125. */
  40126. function TiledGroundGeometry(id, scene,
  40127. /**
  40128. * Defines the minimum value on X axis
  40129. */
  40130. xmin,
  40131. /**
  40132. * Defines the minimum value on Z axis
  40133. */
  40134. zmin,
  40135. /**
  40136. * Defines the maximum value on X axis
  40137. */
  40138. xmax,
  40139. /**
  40140. * Defines the maximum value on Z axis
  40141. */
  40142. zmax,
  40143. /**
  40144. * Defines the subdivisions to apply to the ground
  40145. */
  40146. subdivisions,
  40147. /**
  40148. * Defines the precision to use when computing the tiles
  40149. */
  40150. precision, canBeRegenerated, mesh) {
  40151. if (mesh === void 0) { mesh = null; }
  40152. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40153. _this.xmin = xmin;
  40154. _this.zmin = zmin;
  40155. _this.xmax = xmax;
  40156. _this.zmax = zmax;
  40157. _this.subdivisions = subdivisions;
  40158. _this.precision = precision;
  40159. return _this;
  40160. }
  40161. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40162. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40163. };
  40164. TiledGroundGeometry.prototype.copy = function (id) {
  40165. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40166. };
  40167. return TiledGroundGeometry;
  40168. }(_PrimitiveGeometry));
  40169. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40170. /**
  40171. * Creates a plane geometry
  40172. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40173. */
  40174. var PlaneGeometry = /** @class */ (function (_super) {
  40175. __extends(PlaneGeometry, _super);
  40176. /**
  40177. * Creates a plane geometry
  40178. * @param id defines the unique ID of the geometry
  40179. * @param scene defines the hosting scene
  40180. * @param size defines the size of the plane (width === height)
  40181. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40182. * @param mesh defines the hosting mesh (can be null)
  40183. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40184. */
  40185. function PlaneGeometry(id, scene,
  40186. /**
  40187. * Defines the size of the plane (width === height)
  40188. */
  40189. size, canBeRegenerated, mesh,
  40190. /**
  40191. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40192. */
  40193. side) {
  40194. if (mesh === void 0) { mesh = null; }
  40195. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40196. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40197. _this.size = size;
  40198. _this.side = side;
  40199. return _this;
  40200. }
  40201. PlaneGeometry.prototype._regenerateVertexData = function () {
  40202. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40203. };
  40204. PlaneGeometry.prototype.copy = function (id) {
  40205. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40206. };
  40207. PlaneGeometry.prototype.serialize = function () {
  40208. var serializationObject = _super.prototype.serialize.call(this);
  40209. serializationObject.size = this.size;
  40210. return serializationObject;
  40211. };
  40212. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40213. if (scene.getGeometryByID(parsedPlane.id)) {
  40214. return null; // null since geometry could be something else than a ground...
  40215. }
  40216. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40217. if (BABYLON.Tags) {
  40218. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40219. }
  40220. scene.pushGeometry(plane, true);
  40221. return plane;
  40222. };
  40223. return PlaneGeometry;
  40224. }(_PrimitiveGeometry));
  40225. BABYLON.PlaneGeometry = PlaneGeometry;
  40226. /**
  40227. * Creates a torus knot geometry
  40228. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40229. */
  40230. var TorusKnotGeometry = /** @class */ (function (_super) {
  40231. __extends(TorusKnotGeometry, _super);
  40232. /**
  40233. * Creates a torus knot geometry
  40234. * @param id defines the unique ID of the geometry
  40235. * @param scene defines the hosting scene
  40236. * @param radius defines the radius of the torus knot
  40237. * @param tube defines the thickness of the torus knot tube
  40238. * @param radialSegments defines the number of radial segments
  40239. * @param tubularSegments defines the number of tubular segments
  40240. * @param p defines the first number of windings
  40241. * @param q defines the second number of windings
  40242. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40243. * @param mesh defines the hosting mesh (can be null)
  40244. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40245. */
  40246. function TorusKnotGeometry(id, scene,
  40247. /**
  40248. * Defines the radius of the torus knot
  40249. */
  40250. radius,
  40251. /**
  40252. * Defines the thickness of the torus knot tube
  40253. */
  40254. tube,
  40255. /**
  40256. * Defines the number of radial segments
  40257. */
  40258. radialSegments,
  40259. /**
  40260. * Defines the number of tubular segments
  40261. */
  40262. tubularSegments,
  40263. /**
  40264. * Defines the first number of windings
  40265. */
  40266. p,
  40267. /**
  40268. * Defines the second number of windings
  40269. */
  40270. q, canBeRegenerated, mesh,
  40271. /**
  40272. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40273. */
  40274. side) {
  40275. if (mesh === void 0) { mesh = null; }
  40276. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40277. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40278. _this.radius = radius;
  40279. _this.tube = tube;
  40280. _this.radialSegments = radialSegments;
  40281. _this.tubularSegments = tubularSegments;
  40282. _this.p = p;
  40283. _this.q = q;
  40284. _this.side = side;
  40285. return _this;
  40286. }
  40287. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40288. 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 });
  40289. };
  40290. TorusKnotGeometry.prototype.copy = function (id) {
  40291. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40292. };
  40293. TorusKnotGeometry.prototype.serialize = function () {
  40294. var serializationObject = _super.prototype.serialize.call(this);
  40295. serializationObject.radius = this.radius;
  40296. serializationObject.tube = this.tube;
  40297. serializationObject.radialSegments = this.radialSegments;
  40298. serializationObject.tubularSegments = this.tubularSegments;
  40299. serializationObject.p = this.p;
  40300. serializationObject.q = this.q;
  40301. return serializationObject;
  40302. };
  40303. ;
  40304. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40305. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40306. return null; // null since geometry could be something else than a ground...
  40307. }
  40308. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40309. if (BABYLON.Tags) {
  40310. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40311. }
  40312. scene.pushGeometry(torusKnot, true);
  40313. return torusKnot;
  40314. };
  40315. return TorusKnotGeometry;
  40316. }(_PrimitiveGeometry));
  40317. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40318. //}
  40319. })(BABYLON || (BABYLON = {}));
  40320. //# sourceMappingURL=babylon.geometry.js.map
  40321. var BABYLON;
  40322. (function (BABYLON) {
  40323. /**
  40324. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40325. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40326. */
  40327. var PostProcessManager = /** @class */ (function () {
  40328. /**
  40329. * Creates a new instance PostProcess
  40330. * @param scene The scene that the post process is associated with.
  40331. */
  40332. function PostProcessManager(scene) {
  40333. this._vertexBuffers = {};
  40334. this._scene = scene;
  40335. }
  40336. PostProcessManager.prototype._prepareBuffers = function () {
  40337. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40338. return;
  40339. }
  40340. // VBO
  40341. var vertices = [];
  40342. vertices.push(1, 1);
  40343. vertices.push(-1, 1);
  40344. vertices.push(-1, -1);
  40345. vertices.push(1, -1);
  40346. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40347. this._buildIndexBuffer();
  40348. };
  40349. PostProcessManager.prototype._buildIndexBuffer = function () {
  40350. // Indices
  40351. var indices = [];
  40352. indices.push(0);
  40353. indices.push(1);
  40354. indices.push(2);
  40355. indices.push(0);
  40356. indices.push(2);
  40357. indices.push(3);
  40358. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40359. };
  40360. /**
  40361. * Rebuilds the vertex buffers of the manager.
  40362. */
  40363. PostProcessManager.prototype._rebuild = function () {
  40364. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40365. if (!vb) {
  40366. return;
  40367. }
  40368. vb._rebuild();
  40369. this._buildIndexBuffer();
  40370. };
  40371. // Methods
  40372. /**
  40373. * Prepares a frame to be run through a post process.
  40374. * @param sourceTexture The input texture to the post procesess. (default: null)
  40375. * @param postProcesses An array of post processes to be run. (default: null)
  40376. * @returns True if the post processes were able to be run.
  40377. */
  40378. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40379. if (sourceTexture === void 0) { sourceTexture = null; }
  40380. if (postProcesses === void 0) { postProcesses = null; }
  40381. var camera = this._scene.activeCamera;
  40382. if (!camera) {
  40383. return false;
  40384. }
  40385. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40386. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40387. return false;
  40388. }
  40389. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40390. return true;
  40391. };
  40392. /**
  40393. * Manually render a set of post processes to a texture.
  40394. * @param postProcesses An array of post processes to be run.
  40395. * @param targetTexture The target texture to render to.
  40396. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40397. */
  40398. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40399. if (targetTexture === void 0) { targetTexture = null; }
  40400. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40401. var engine = this._scene.getEngine();
  40402. for (var index = 0; index < postProcesses.length; index++) {
  40403. if (index < postProcesses.length - 1) {
  40404. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40405. }
  40406. else {
  40407. if (targetTexture) {
  40408. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40409. }
  40410. else {
  40411. engine.restoreDefaultFramebuffer();
  40412. }
  40413. }
  40414. var pp = postProcesses[index];
  40415. var effect = pp.apply();
  40416. if (effect) {
  40417. pp.onBeforeRenderObservable.notifyObservers(effect);
  40418. // VBOs
  40419. this._prepareBuffers();
  40420. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40421. // Draw order
  40422. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40423. pp.onAfterRenderObservable.notifyObservers(effect);
  40424. }
  40425. }
  40426. // Restore depth buffer
  40427. engine.setDepthBuffer(true);
  40428. engine.setDepthWrite(true);
  40429. };
  40430. /**
  40431. * Finalize the result of the output of the postprocesses.
  40432. * @param doNotPresent If true the result will not be displayed to the screen.
  40433. * @param targetTexture The target texture to render to.
  40434. * @param faceIndex The index of the face to bind the target texture to.
  40435. * @param postProcesses The array of post processes to render.
  40436. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40437. */
  40438. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40439. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40440. var camera = this._scene.activeCamera;
  40441. if (!camera) {
  40442. return;
  40443. }
  40444. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40445. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40446. return;
  40447. }
  40448. var engine = this._scene.getEngine();
  40449. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40450. var pp = postProcesses[index];
  40451. if (index < len - 1) {
  40452. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40453. }
  40454. else {
  40455. if (targetTexture) {
  40456. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40457. pp._outputTexture = targetTexture;
  40458. }
  40459. else {
  40460. engine.restoreDefaultFramebuffer();
  40461. pp._outputTexture = null;
  40462. }
  40463. }
  40464. if (doNotPresent) {
  40465. break;
  40466. }
  40467. var effect = pp.apply();
  40468. if (effect) {
  40469. pp.onBeforeRenderObservable.notifyObservers(effect);
  40470. // VBOs
  40471. this._prepareBuffers();
  40472. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40473. // Draw order
  40474. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40475. pp.onAfterRenderObservable.notifyObservers(effect);
  40476. }
  40477. }
  40478. // Restore states
  40479. engine.setDepthBuffer(true);
  40480. engine.setDepthWrite(true);
  40481. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40482. };
  40483. /**
  40484. * Disposes of the post process manager.
  40485. */
  40486. PostProcessManager.prototype.dispose = function () {
  40487. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40488. if (buffer) {
  40489. buffer.dispose();
  40490. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40491. }
  40492. if (this._indexBuffer) {
  40493. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40494. this._indexBuffer = null;
  40495. }
  40496. };
  40497. return PostProcessManager;
  40498. }());
  40499. BABYLON.PostProcessManager = PostProcessManager;
  40500. })(BABYLON || (BABYLON = {}));
  40501. //# sourceMappingURL=babylon.postProcessManager.js.map
  40502. var BABYLON;
  40503. (function (BABYLON) {
  40504. /**
  40505. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40506. */
  40507. var PerformanceMonitor = /** @class */ (function () {
  40508. /**
  40509. * constructor
  40510. * @param frameSampleSize The number of samples required to saturate the sliding window
  40511. */
  40512. function PerformanceMonitor(frameSampleSize) {
  40513. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40514. this._enabled = true;
  40515. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40516. }
  40517. /**
  40518. * Samples current frame
  40519. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40520. */
  40521. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40522. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40523. if (!this._enabled)
  40524. return;
  40525. if (this._lastFrameTimeMs != null) {
  40526. var dt = timeMs - this._lastFrameTimeMs;
  40527. this._rollingFrameTime.add(dt);
  40528. }
  40529. this._lastFrameTimeMs = timeMs;
  40530. };
  40531. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40532. /**
  40533. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40534. * @return Average frame time in milliseconds
  40535. */
  40536. get: function () {
  40537. return this._rollingFrameTime.average;
  40538. },
  40539. enumerable: true,
  40540. configurable: true
  40541. });
  40542. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40543. /**
  40544. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40545. * @return Frame time variance in milliseconds squared
  40546. */
  40547. get: function () {
  40548. return this._rollingFrameTime.variance;
  40549. },
  40550. enumerable: true,
  40551. configurable: true
  40552. });
  40553. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40554. /**
  40555. * Returns the frame time of the most recent frame
  40556. * @return Frame time in milliseconds
  40557. */
  40558. get: function () {
  40559. return this._rollingFrameTime.history(0);
  40560. },
  40561. enumerable: true,
  40562. configurable: true
  40563. });
  40564. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40565. /**
  40566. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40567. * @return Framerate in frames per second
  40568. */
  40569. get: function () {
  40570. return 1000.0 / this._rollingFrameTime.average;
  40571. },
  40572. enumerable: true,
  40573. configurable: true
  40574. });
  40575. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40576. /**
  40577. * Returns the average framerate in frames per second using the most recent frame time
  40578. * @return Framerate in frames per second
  40579. */
  40580. get: function () {
  40581. var history = this._rollingFrameTime.history(0);
  40582. if (history === 0) {
  40583. return 0;
  40584. }
  40585. return 1000.0 / history;
  40586. },
  40587. enumerable: true,
  40588. configurable: true
  40589. });
  40590. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40591. /**
  40592. * Returns true if enough samples have been taken to completely fill the sliding window
  40593. * @return true if saturated
  40594. */
  40595. get: function () {
  40596. return this._rollingFrameTime.isSaturated();
  40597. },
  40598. enumerable: true,
  40599. configurable: true
  40600. });
  40601. /**
  40602. * Enables contributions to the sliding window sample set
  40603. */
  40604. PerformanceMonitor.prototype.enable = function () {
  40605. this._enabled = true;
  40606. };
  40607. /**
  40608. * Disables contributions to the sliding window sample set
  40609. * Samples will not be interpolated over the disabled period
  40610. */
  40611. PerformanceMonitor.prototype.disable = function () {
  40612. this._enabled = false;
  40613. //clear last sample to avoid interpolating over the disabled period when next enabled
  40614. this._lastFrameTimeMs = null;
  40615. };
  40616. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40617. /**
  40618. * Returns true if sampling is enabled
  40619. * @return true if enabled
  40620. */
  40621. get: function () {
  40622. return this._enabled;
  40623. },
  40624. enumerable: true,
  40625. configurable: true
  40626. });
  40627. /**
  40628. * Resets performance monitor
  40629. */
  40630. PerformanceMonitor.prototype.reset = function () {
  40631. //clear last sample to avoid interpolating over the disabled period when next enabled
  40632. this._lastFrameTimeMs = null;
  40633. //wipe record
  40634. this._rollingFrameTime.reset();
  40635. };
  40636. return PerformanceMonitor;
  40637. }());
  40638. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40639. /**
  40640. * RollingAverage
  40641. *
  40642. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40643. */
  40644. var RollingAverage = /** @class */ (function () {
  40645. /**
  40646. * constructor
  40647. * @param length The number of samples required to saturate the sliding window
  40648. */
  40649. function RollingAverage(length) {
  40650. this._samples = new Array(length);
  40651. this.reset();
  40652. }
  40653. /**
  40654. * Adds a sample to the sample set
  40655. * @param v The sample value
  40656. */
  40657. RollingAverage.prototype.add = function (v) {
  40658. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40659. var delta;
  40660. //we need to check if we've already wrapped round
  40661. if (this.isSaturated()) {
  40662. //remove bottom of stack from mean
  40663. var bottomValue = this._samples[this._pos];
  40664. delta = bottomValue - this.average;
  40665. this.average -= delta / (this._sampleCount - 1);
  40666. this._m2 -= delta * (bottomValue - this.average);
  40667. }
  40668. else {
  40669. this._sampleCount++;
  40670. }
  40671. //add new value to mean
  40672. delta = v - this.average;
  40673. this.average += delta / (this._sampleCount);
  40674. this._m2 += delta * (v - this.average);
  40675. //set the new variance
  40676. this.variance = this._m2 / (this._sampleCount - 1);
  40677. this._samples[this._pos] = v;
  40678. this._pos++;
  40679. this._pos %= this._samples.length; //positive wrap around
  40680. };
  40681. /**
  40682. * Returns previously added values or null if outside of history or outside the sliding window domain
  40683. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40684. * @return Value previously recorded with add() or null if outside of range
  40685. */
  40686. RollingAverage.prototype.history = function (i) {
  40687. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40688. return 0;
  40689. }
  40690. var i0 = this._wrapPosition(this._pos - 1.0);
  40691. return this._samples[this._wrapPosition(i0 - i)];
  40692. };
  40693. /**
  40694. * Returns true if enough samples have been taken to completely fill the sliding window
  40695. * @return true if sample-set saturated
  40696. */
  40697. RollingAverage.prototype.isSaturated = function () {
  40698. return this._sampleCount >= this._samples.length;
  40699. };
  40700. /**
  40701. * Resets the rolling average (equivalent to 0 samples taken so far)
  40702. */
  40703. RollingAverage.prototype.reset = function () {
  40704. this.average = 0;
  40705. this.variance = 0;
  40706. this._sampleCount = 0;
  40707. this._pos = 0;
  40708. this._m2 = 0;
  40709. };
  40710. /**
  40711. * Wraps a value around the sample range boundaries
  40712. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40713. * @return Wrapped position in sample range
  40714. */
  40715. RollingAverage.prototype._wrapPosition = function (i) {
  40716. var max = this._samples.length;
  40717. return ((i % max) + max) % max;
  40718. };
  40719. return RollingAverage;
  40720. }());
  40721. BABYLON.RollingAverage = RollingAverage;
  40722. })(BABYLON || (BABYLON = {}));
  40723. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40724. var BABYLON;
  40725. (function (BABYLON) {
  40726. /**
  40727. * This groups together the common properties used for image processing either in direct forward pass
  40728. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40729. * or not.
  40730. */
  40731. var ImageProcessingConfiguration = /** @class */ (function () {
  40732. function ImageProcessingConfiguration() {
  40733. /**
  40734. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40735. */
  40736. this.colorCurves = new BABYLON.ColorCurves();
  40737. this._colorCurvesEnabled = false;
  40738. this._colorGradingEnabled = false;
  40739. this._colorGradingWithGreenDepth = true;
  40740. this._colorGradingBGR = true;
  40741. this._exposure = 1.0;
  40742. this._toneMappingEnabled = false;
  40743. this._contrast = 1.0;
  40744. /**
  40745. * Vignette stretch size.
  40746. */
  40747. this.vignetteStretch = 0;
  40748. /**
  40749. * Vignette centre X Offset.
  40750. */
  40751. this.vignetteCentreX = 0;
  40752. /**
  40753. * Vignette centre Y Offset.
  40754. */
  40755. this.vignetteCentreY = 0;
  40756. /**
  40757. * Vignette weight or intensity of the vignette effect.
  40758. */
  40759. this.vignetteWeight = 1.5;
  40760. /**
  40761. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40762. * if vignetteEnabled is set to true.
  40763. */
  40764. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40765. /**
  40766. * Camera field of view used by the Vignette effect.
  40767. */
  40768. this.vignetteCameraFov = 0.5;
  40769. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40770. this._vignetteEnabled = false;
  40771. this._applyByPostProcess = false;
  40772. this._isEnabled = true;
  40773. /**
  40774. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40775. */
  40776. this.onUpdateParameters = new BABYLON.Observable();
  40777. }
  40778. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40779. /**
  40780. * Gets wether the color curves effect is enabled.
  40781. */
  40782. get: function () {
  40783. return this._colorCurvesEnabled;
  40784. },
  40785. /**
  40786. * Sets wether the color curves effect is enabled.
  40787. */
  40788. set: function (value) {
  40789. if (this._colorCurvesEnabled === value) {
  40790. return;
  40791. }
  40792. this._colorCurvesEnabled = value;
  40793. this._updateParameters();
  40794. },
  40795. enumerable: true,
  40796. configurable: true
  40797. });
  40798. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40799. /**
  40800. * Gets wether the color grading effect is enabled.
  40801. */
  40802. get: function () {
  40803. return this._colorGradingEnabled;
  40804. },
  40805. /**
  40806. * Sets wether the color grading effect is enabled.
  40807. */
  40808. set: function (value) {
  40809. if (this._colorGradingEnabled === value) {
  40810. return;
  40811. }
  40812. this._colorGradingEnabled = value;
  40813. this._updateParameters();
  40814. },
  40815. enumerable: true,
  40816. configurable: true
  40817. });
  40818. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40819. /**
  40820. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40821. */
  40822. get: function () {
  40823. return this._colorGradingWithGreenDepth;
  40824. },
  40825. /**
  40826. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40827. */
  40828. set: function (value) {
  40829. if (this._colorGradingWithGreenDepth === value) {
  40830. return;
  40831. }
  40832. this._colorGradingWithGreenDepth = value;
  40833. this._updateParameters();
  40834. },
  40835. enumerable: true,
  40836. configurable: true
  40837. });
  40838. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40839. /**
  40840. * Gets wether the color grading texture contains BGR values.
  40841. */
  40842. get: function () {
  40843. return this._colorGradingBGR;
  40844. },
  40845. /**
  40846. * Sets wether the color grading texture contains BGR values.
  40847. */
  40848. set: function (value) {
  40849. if (this._colorGradingBGR === value) {
  40850. return;
  40851. }
  40852. this._colorGradingBGR = value;
  40853. this._updateParameters();
  40854. },
  40855. enumerable: true,
  40856. configurable: true
  40857. });
  40858. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40859. /**
  40860. * Gets the Exposure used in the effect.
  40861. */
  40862. get: function () {
  40863. return this._exposure;
  40864. },
  40865. /**
  40866. * Sets the Exposure used in the effect.
  40867. */
  40868. set: function (value) {
  40869. if (this._exposure === value) {
  40870. return;
  40871. }
  40872. this._exposure = value;
  40873. this._updateParameters();
  40874. },
  40875. enumerable: true,
  40876. configurable: true
  40877. });
  40878. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40879. /**
  40880. * Gets wether the tone mapping effect is enabled.
  40881. */
  40882. get: function () {
  40883. return this._toneMappingEnabled;
  40884. },
  40885. /**
  40886. * Sets wether the tone mapping effect is enabled.
  40887. */
  40888. set: function (value) {
  40889. if (this._toneMappingEnabled === value) {
  40890. return;
  40891. }
  40892. this._toneMappingEnabled = value;
  40893. this._updateParameters();
  40894. },
  40895. enumerable: true,
  40896. configurable: true
  40897. });
  40898. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40899. /**
  40900. * Gets the contrast used in the effect.
  40901. */
  40902. get: function () {
  40903. return this._contrast;
  40904. },
  40905. /**
  40906. * Sets the contrast used in the effect.
  40907. */
  40908. set: function (value) {
  40909. if (this._contrast === value) {
  40910. return;
  40911. }
  40912. this._contrast = value;
  40913. this._updateParameters();
  40914. },
  40915. enumerable: true,
  40916. configurable: true
  40917. });
  40918. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40919. /**
  40920. * Gets the vignette blend mode allowing different kind of effect.
  40921. */
  40922. get: function () {
  40923. return this._vignetteBlendMode;
  40924. },
  40925. /**
  40926. * Sets the vignette blend mode allowing different kind of effect.
  40927. */
  40928. set: function (value) {
  40929. if (this._vignetteBlendMode === value) {
  40930. return;
  40931. }
  40932. this._vignetteBlendMode = value;
  40933. this._updateParameters();
  40934. },
  40935. enumerable: true,
  40936. configurable: true
  40937. });
  40938. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40939. /**
  40940. * Gets wether the vignette effect is enabled.
  40941. */
  40942. get: function () {
  40943. return this._vignetteEnabled;
  40944. },
  40945. /**
  40946. * Sets wether the vignette effect is enabled.
  40947. */
  40948. set: function (value) {
  40949. if (this._vignetteEnabled === value) {
  40950. return;
  40951. }
  40952. this._vignetteEnabled = value;
  40953. this._updateParameters();
  40954. },
  40955. enumerable: true,
  40956. configurable: true
  40957. });
  40958. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40959. /**
  40960. * Gets wether the image processing is applied through a post process or not.
  40961. */
  40962. get: function () {
  40963. return this._applyByPostProcess;
  40964. },
  40965. /**
  40966. * Sets wether the image processing is applied through a post process or not.
  40967. */
  40968. set: function (value) {
  40969. if (this._applyByPostProcess === value) {
  40970. return;
  40971. }
  40972. this._applyByPostProcess = value;
  40973. this._updateParameters();
  40974. },
  40975. enumerable: true,
  40976. configurable: true
  40977. });
  40978. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40979. /**
  40980. * Gets wether the image processing is enabled or not.
  40981. */
  40982. get: function () {
  40983. return this._isEnabled;
  40984. },
  40985. /**
  40986. * Sets wether the image processing is enabled or not.
  40987. */
  40988. set: function (value) {
  40989. if (this._isEnabled === value) {
  40990. return;
  40991. }
  40992. this._isEnabled = value;
  40993. this._updateParameters();
  40994. },
  40995. enumerable: true,
  40996. configurable: true
  40997. });
  40998. /**
  40999. * Method called each time the image processing information changes requires to recompile the effect.
  41000. */
  41001. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41002. this.onUpdateParameters.notifyObservers(this);
  41003. };
  41004. ImageProcessingConfiguration.prototype.getClassName = function () {
  41005. return "ImageProcessingConfiguration";
  41006. };
  41007. /**
  41008. * Prepare the list of uniforms associated with the Image Processing effects.
  41009. * @param uniformsList The list of uniforms used in the effect
  41010. * @param defines the list of defines currently in use
  41011. */
  41012. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41013. if (defines.EXPOSURE) {
  41014. uniforms.push("exposureLinear");
  41015. }
  41016. if (defines.CONTRAST) {
  41017. uniforms.push("contrast");
  41018. }
  41019. if (defines.COLORGRADING) {
  41020. uniforms.push("colorTransformSettings");
  41021. }
  41022. if (defines.VIGNETTE) {
  41023. uniforms.push("vInverseScreenSize");
  41024. uniforms.push("vignetteSettings1");
  41025. uniforms.push("vignetteSettings2");
  41026. }
  41027. if (defines.COLORCURVES) {
  41028. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41029. }
  41030. };
  41031. /**
  41032. * Prepare the list of samplers associated with the Image Processing effects.
  41033. * @param uniformsList The list of uniforms used in the effect
  41034. * @param defines the list of defines currently in use
  41035. */
  41036. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41037. if (defines.COLORGRADING) {
  41038. samplersList.push("txColorTransform");
  41039. }
  41040. };
  41041. /**
  41042. * Prepare the list of defines associated to the shader.
  41043. * @param defines the list of defines to complete
  41044. */
  41045. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41046. if (forPostProcess === void 0) { forPostProcess = false; }
  41047. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41048. defines.VIGNETTE = false;
  41049. defines.TONEMAPPING = false;
  41050. defines.CONTRAST = false;
  41051. defines.EXPOSURE = false;
  41052. defines.COLORCURVES = false;
  41053. defines.COLORGRADING = false;
  41054. defines.COLORGRADING3D = false;
  41055. defines.IMAGEPROCESSING = false;
  41056. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41057. return;
  41058. }
  41059. defines.VIGNETTE = this.vignetteEnabled;
  41060. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41061. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41062. defines.TONEMAPPING = this.toneMappingEnabled;
  41063. defines.CONTRAST = (this.contrast !== 1.0);
  41064. defines.EXPOSURE = (this.exposure !== 1.0);
  41065. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41066. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41067. if (defines.COLORGRADING) {
  41068. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41069. }
  41070. else {
  41071. defines.COLORGRADING3D = false;
  41072. }
  41073. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41074. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41075. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41076. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41077. };
  41078. /**
  41079. * Returns true if all the image processing information are ready.
  41080. */
  41081. ImageProcessingConfiguration.prototype.isReady = function () {
  41082. // Color Grading texure can not be none blocking.
  41083. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41084. };
  41085. /**
  41086. * Binds the image processing to the shader.
  41087. * @param effect The effect to bind to
  41088. */
  41089. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41090. if (aspectRatio === void 0) { aspectRatio = 1; }
  41091. // Color Curves
  41092. if (this._colorCurvesEnabled && this.colorCurves) {
  41093. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41094. }
  41095. // Vignette
  41096. if (this._vignetteEnabled) {
  41097. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41098. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41099. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41100. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41101. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41102. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41103. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41104. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41105. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41106. var vignettePower = -2.0 * this.vignetteWeight;
  41107. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41108. }
  41109. // Exposure
  41110. effect.setFloat("exposureLinear", this.exposure);
  41111. // Contrast
  41112. effect.setFloat("contrast", this.contrast);
  41113. // Color transform settings
  41114. if (this.colorGradingTexture) {
  41115. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41116. var textureSize = this.colorGradingTexture.getSize().height;
  41117. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41118. 0.5 / textureSize, // textureOffset
  41119. textureSize, // textureSize
  41120. this.colorGradingTexture.level // weight
  41121. );
  41122. }
  41123. };
  41124. /**
  41125. * Clones the current image processing instance.
  41126. * @return The cloned image processing
  41127. */
  41128. ImageProcessingConfiguration.prototype.clone = function () {
  41129. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41130. };
  41131. /**
  41132. * Serializes the current image processing instance to a json representation.
  41133. * @return a JSON representation
  41134. */
  41135. ImageProcessingConfiguration.prototype.serialize = function () {
  41136. return BABYLON.SerializationHelper.Serialize(this);
  41137. };
  41138. /**
  41139. * Parses the image processing from a json representation.
  41140. * @param source the JSON source to parse
  41141. * @return The parsed image processing
  41142. */
  41143. ImageProcessingConfiguration.Parse = function (source) {
  41144. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41145. };
  41146. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41147. /**
  41148. * Used to apply the vignette as a mix with the pixel color.
  41149. */
  41150. get: function () {
  41151. return this._VIGNETTEMODE_MULTIPLY;
  41152. },
  41153. enumerable: true,
  41154. configurable: true
  41155. });
  41156. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41157. /**
  41158. * Used to apply the vignette as a replacement of the pixel color.
  41159. */
  41160. get: function () {
  41161. return this._VIGNETTEMODE_OPAQUE;
  41162. },
  41163. enumerable: true,
  41164. configurable: true
  41165. });
  41166. // Static constants associated to the image processing.
  41167. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41168. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41169. __decorate([
  41170. BABYLON.serializeAsColorCurves()
  41171. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41172. __decorate([
  41173. BABYLON.serialize()
  41174. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41175. __decorate([
  41176. BABYLON.serializeAsTexture()
  41177. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41178. __decorate([
  41179. BABYLON.serialize()
  41180. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41181. __decorate([
  41182. BABYLON.serialize()
  41183. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41184. __decorate([
  41185. BABYLON.serialize()
  41186. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41187. __decorate([
  41188. BABYLON.serialize()
  41189. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41190. __decorate([
  41191. BABYLON.serialize()
  41192. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41193. __decorate([
  41194. BABYLON.serialize()
  41195. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41196. __decorate([
  41197. BABYLON.serialize()
  41198. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41199. __decorate([
  41200. BABYLON.serialize()
  41201. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41202. __decorate([
  41203. BABYLON.serialize()
  41204. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41205. __decorate([
  41206. BABYLON.serialize()
  41207. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41208. __decorate([
  41209. BABYLON.serializeAsColor4()
  41210. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41211. __decorate([
  41212. BABYLON.serialize()
  41213. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41214. __decorate([
  41215. BABYLON.serialize()
  41216. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41217. __decorate([
  41218. BABYLON.serialize()
  41219. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41220. __decorate([
  41221. BABYLON.serialize()
  41222. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41223. __decorate([
  41224. BABYLON.serialize()
  41225. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41226. return ImageProcessingConfiguration;
  41227. }());
  41228. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41229. })(BABYLON || (BABYLON = {}));
  41230. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41231. var BABYLON;
  41232. (function (BABYLON) {
  41233. /**
  41234. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41235. * It can help converting any input color in a desired output one. This can then be used to create effects
  41236. * from sepia, black and white to sixties or futuristic rendering...
  41237. *
  41238. * The only supported format is currently 3dl.
  41239. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41240. */
  41241. var ColorGradingTexture = /** @class */ (function (_super) {
  41242. __extends(ColorGradingTexture, _super);
  41243. /**
  41244. * Instantiates a ColorGradingTexture from the following parameters.
  41245. *
  41246. * @param url The location of the color gradind data (currently only supporting 3dl)
  41247. * @param scene The scene the texture will be used in
  41248. */
  41249. function ColorGradingTexture(url, scene) {
  41250. var _this = _super.call(this, scene) || this;
  41251. if (!url) {
  41252. return _this;
  41253. }
  41254. _this._engine = scene.getEngine();
  41255. _this._textureMatrix = BABYLON.Matrix.Identity();
  41256. _this.name = url;
  41257. _this.url = url;
  41258. _this.hasAlpha = false;
  41259. _this.isCube = false;
  41260. _this.is3D = _this._engine.webGLVersion > 1;
  41261. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41262. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41263. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41264. _this.anisotropicFilteringLevel = 1;
  41265. _this._texture = _this._getFromCache(url, true);
  41266. if (!_this._texture) {
  41267. if (!scene.useDelayedTextureLoading) {
  41268. _this.loadTexture();
  41269. }
  41270. else {
  41271. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41272. }
  41273. }
  41274. return _this;
  41275. }
  41276. /**
  41277. * Returns the texture matrix used in most of the material.
  41278. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41279. */
  41280. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41281. return this._textureMatrix;
  41282. };
  41283. /**
  41284. * Occurs when the file being loaded is a .3dl LUT file.
  41285. */
  41286. ColorGradingTexture.prototype.load3dlTexture = function () {
  41287. var engine = this._engine;
  41288. var texture;
  41289. if (engine.webGLVersion === 1) {
  41290. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41291. }
  41292. else {
  41293. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41294. }
  41295. this._texture = texture;
  41296. var callback = function (text) {
  41297. if (typeof text !== "string") {
  41298. return;
  41299. }
  41300. var data = null;
  41301. var tempData = null;
  41302. var line;
  41303. var lines = text.split('\n');
  41304. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41305. var maxColor = 0;
  41306. for (var i = 0; i < lines.length; i++) {
  41307. line = lines[i];
  41308. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41309. continue;
  41310. if (line.indexOf('#') === 0)
  41311. continue;
  41312. var words = line.split(" ");
  41313. if (size === 0) {
  41314. // Number of space + one
  41315. size = words.length;
  41316. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41317. tempData = new Float32Array(size * size * size * 4);
  41318. continue;
  41319. }
  41320. if (size != 0) {
  41321. var r = Math.max(parseInt(words[0]), 0);
  41322. var g = Math.max(parseInt(words[1]), 0);
  41323. var b = Math.max(parseInt(words[2]), 0);
  41324. maxColor = Math.max(r, maxColor);
  41325. maxColor = Math.max(g, maxColor);
  41326. maxColor = Math.max(b, maxColor);
  41327. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41328. if (tempData) {
  41329. tempData[pixelStorageIndex + 0] = r;
  41330. tempData[pixelStorageIndex + 1] = g;
  41331. tempData[pixelStorageIndex + 2] = b;
  41332. }
  41333. pixelIndexSlice++;
  41334. if (pixelIndexSlice % size == 0) {
  41335. pixelIndexH++;
  41336. pixelIndexSlice = 0;
  41337. if (pixelIndexH % size == 0) {
  41338. pixelIndexW++;
  41339. pixelIndexH = 0;
  41340. }
  41341. }
  41342. }
  41343. }
  41344. if (tempData && data) {
  41345. for (var i = 0; i < tempData.length; i++) {
  41346. if (i > 0 && (i + 1) % 4 === 0) {
  41347. data[i] = 255;
  41348. }
  41349. else {
  41350. var value = tempData[i];
  41351. data[i] = (value / maxColor * 255);
  41352. }
  41353. }
  41354. }
  41355. if (texture.is3D) {
  41356. texture.updateSize(size, size, size);
  41357. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41358. }
  41359. else {
  41360. texture.updateSize(size * size, size);
  41361. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41362. }
  41363. };
  41364. var scene = this.getScene();
  41365. if (scene) {
  41366. scene._loadFile(this.url, callback);
  41367. }
  41368. else {
  41369. this._engine._loadFile(this.url, callback);
  41370. }
  41371. return this._texture;
  41372. };
  41373. /**
  41374. * Starts the loading process of the texture.
  41375. */
  41376. ColorGradingTexture.prototype.loadTexture = function () {
  41377. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41378. this.load3dlTexture();
  41379. }
  41380. };
  41381. /**
  41382. * Clones the color gradind texture.
  41383. */
  41384. ColorGradingTexture.prototype.clone = function () {
  41385. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41386. // Base texture
  41387. newTexture.level = this.level;
  41388. return newTexture;
  41389. };
  41390. /**
  41391. * Called during delayed load for textures.
  41392. */
  41393. ColorGradingTexture.prototype.delayLoad = function () {
  41394. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41395. return;
  41396. }
  41397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41398. this._texture = this._getFromCache(this.url, true);
  41399. if (!this._texture) {
  41400. this.loadTexture();
  41401. }
  41402. };
  41403. /**
  41404. * Parses a color grading texture serialized by Babylon.
  41405. * @param parsedTexture The texture information being parsedTexture
  41406. * @param scene The scene to load the texture in
  41407. * @param rootUrl The root url of the data assets to load
  41408. * @return A color gradind texture
  41409. */
  41410. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41411. var texture = null;
  41412. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41413. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41414. texture.name = parsedTexture.name;
  41415. texture.level = parsedTexture.level;
  41416. }
  41417. return texture;
  41418. };
  41419. /**
  41420. * Serializes the LUT texture to json format.
  41421. */
  41422. ColorGradingTexture.prototype.serialize = function () {
  41423. if (!this.name) {
  41424. return null;
  41425. }
  41426. var serializationObject = {};
  41427. serializationObject.name = this.name;
  41428. serializationObject.level = this.level;
  41429. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41430. return serializationObject;
  41431. };
  41432. /**
  41433. * Empty line regex stored for GC.
  41434. */
  41435. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41436. return ColorGradingTexture;
  41437. }(BABYLON.BaseTexture));
  41438. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41439. })(BABYLON || (BABYLON = {}));
  41440. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41441. var BABYLON;
  41442. (function (BABYLON) {
  41443. /**
  41444. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41445. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41446. * 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;
  41447. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41448. */
  41449. var ColorCurves = /** @class */ (function () {
  41450. function ColorCurves() {
  41451. this._dirty = true;
  41452. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41453. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41454. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41455. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41456. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41457. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41458. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41459. this._globalHue = 30;
  41460. this._globalDensity = 0;
  41461. this._globalSaturation = 0;
  41462. this._globalExposure = 0;
  41463. this._highlightsHue = 30;
  41464. this._highlightsDensity = 0;
  41465. this._highlightsSaturation = 0;
  41466. this._highlightsExposure = 0;
  41467. this._midtonesHue = 30;
  41468. this._midtonesDensity = 0;
  41469. this._midtonesSaturation = 0;
  41470. this._midtonesExposure = 0;
  41471. this._shadowsHue = 30;
  41472. this._shadowsDensity = 0;
  41473. this._shadowsSaturation = 0;
  41474. this._shadowsExposure = 0;
  41475. }
  41476. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41477. /**
  41478. * Gets the global Hue value.
  41479. * 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).
  41480. */
  41481. get: function () {
  41482. return this._globalHue;
  41483. },
  41484. /**
  41485. * Sets the global Hue value.
  41486. * 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).
  41487. */
  41488. set: function (value) {
  41489. this._globalHue = value;
  41490. this._dirty = true;
  41491. },
  41492. enumerable: true,
  41493. configurable: true
  41494. });
  41495. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41496. /**
  41497. * Gets the global Density value.
  41498. * 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.
  41499. * Values less than zero provide a filter of opposite hue.
  41500. */
  41501. get: function () {
  41502. return this._globalDensity;
  41503. },
  41504. /**
  41505. * Sets the global Density value.
  41506. * 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.
  41507. * Values less than zero provide a filter of opposite hue.
  41508. */
  41509. set: function (value) {
  41510. this._globalDensity = value;
  41511. this._dirty = true;
  41512. },
  41513. enumerable: true,
  41514. configurable: true
  41515. });
  41516. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41517. /**
  41518. * Gets the global Saturation value.
  41519. * 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.
  41520. */
  41521. get: function () {
  41522. return this._globalSaturation;
  41523. },
  41524. /**
  41525. * Sets the global Saturation value.
  41526. * 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.
  41527. */
  41528. set: function (value) {
  41529. this._globalSaturation = value;
  41530. this._dirty = true;
  41531. },
  41532. enumerable: true,
  41533. configurable: true
  41534. });
  41535. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41536. /**
  41537. * Gets the highlights Hue value.
  41538. * 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).
  41539. */
  41540. get: function () {
  41541. return this._highlightsHue;
  41542. },
  41543. /**
  41544. * Sets the highlights Hue value.
  41545. * 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).
  41546. */
  41547. set: function (value) {
  41548. this._highlightsHue = value;
  41549. this._dirty = true;
  41550. },
  41551. enumerable: true,
  41552. configurable: true
  41553. });
  41554. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41555. /**
  41556. * Gets the highlights Density value.
  41557. * 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.
  41558. * Values less than zero provide a filter of opposite hue.
  41559. */
  41560. get: function () {
  41561. return this._highlightsDensity;
  41562. },
  41563. /**
  41564. * Sets the highlights Density value.
  41565. * 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.
  41566. * Values less than zero provide a filter of opposite hue.
  41567. */
  41568. set: function (value) {
  41569. this._highlightsDensity = value;
  41570. this._dirty = true;
  41571. },
  41572. enumerable: true,
  41573. configurable: true
  41574. });
  41575. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41576. /**
  41577. * Gets the highlights Saturation value.
  41578. * 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.
  41579. */
  41580. get: function () {
  41581. return this._highlightsSaturation;
  41582. },
  41583. /**
  41584. * Sets the highlights Saturation value.
  41585. * 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.
  41586. */
  41587. set: function (value) {
  41588. this._highlightsSaturation = value;
  41589. this._dirty = true;
  41590. },
  41591. enumerable: true,
  41592. configurable: true
  41593. });
  41594. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41595. /**
  41596. * Gets the highlights Exposure value.
  41597. * 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.
  41598. */
  41599. get: function () {
  41600. return this._highlightsExposure;
  41601. },
  41602. /**
  41603. * Sets the highlights Exposure value.
  41604. * 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.
  41605. */
  41606. set: function (value) {
  41607. this._highlightsExposure = value;
  41608. this._dirty = true;
  41609. },
  41610. enumerable: true,
  41611. configurable: true
  41612. });
  41613. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41614. /**
  41615. * Gets the midtones Hue value.
  41616. * 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).
  41617. */
  41618. get: function () {
  41619. return this._midtonesHue;
  41620. },
  41621. /**
  41622. * Sets the midtones Hue value.
  41623. * 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).
  41624. */
  41625. set: function (value) {
  41626. this._midtonesHue = value;
  41627. this._dirty = true;
  41628. },
  41629. enumerable: true,
  41630. configurable: true
  41631. });
  41632. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41633. /**
  41634. * Gets the midtones Density value.
  41635. * 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.
  41636. * Values less than zero provide a filter of opposite hue.
  41637. */
  41638. get: function () {
  41639. return this._midtonesDensity;
  41640. },
  41641. /**
  41642. * Sets the midtones Density value.
  41643. * 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.
  41644. * Values less than zero provide a filter of opposite hue.
  41645. */
  41646. set: function (value) {
  41647. this._midtonesDensity = value;
  41648. this._dirty = true;
  41649. },
  41650. enumerable: true,
  41651. configurable: true
  41652. });
  41653. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41654. /**
  41655. * Gets the midtones Saturation value.
  41656. * 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.
  41657. */
  41658. get: function () {
  41659. return this._midtonesSaturation;
  41660. },
  41661. /**
  41662. * Sets the midtones Saturation value.
  41663. * 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.
  41664. */
  41665. set: function (value) {
  41666. this._midtonesSaturation = value;
  41667. this._dirty = true;
  41668. },
  41669. enumerable: true,
  41670. configurable: true
  41671. });
  41672. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41673. /**
  41674. * Gets the midtones Exposure value.
  41675. * 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.
  41676. */
  41677. get: function () {
  41678. return this._midtonesExposure;
  41679. },
  41680. /**
  41681. * Sets the midtones Exposure value.
  41682. * 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.
  41683. */
  41684. set: function (value) {
  41685. this._midtonesExposure = value;
  41686. this._dirty = true;
  41687. },
  41688. enumerable: true,
  41689. configurable: true
  41690. });
  41691. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41692. /**
  41693. * Gets the shadows Hue value.
  41694. * 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).
  41695. */
  41696. get: function () {
  41697. return this._shadowsHue;
  41698. },
  41699. /**
  41700. * Sets the shadows Hue value.
  41701. * 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).
  41702. */
  41703. set: function (value) {
  41704. this._shadowsHue = value;
  41705. this._dirty = true;
  41706. },
  41707. enumerable: true,
  41708. configurable: true
  41709. });
  41710. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41711. /**
  41712. * Gets the shadows Density value.
  41713. * 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.
  41714. * Values less than zero provide a filter of opposite hue.
  41715. */
  41716. get: function () {
  41717. return this._shadowsDensity;
  41718. },
  41719. /**
  41720. * Sets the shadows Density value.
  41721. * 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.
  41722. * Values less than zero provide a filter of opposite hue.
  41723. */
  41724. set: function (value) {
  41725. this._shadowsDensity = value;
  41726. this._dirty = true;
  41727. },
  41728. enumerable: true,
  41729. configurable: true
  41730. });
  41731. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41732. /**
  41733. * Gets the shadows Saturation value.
  41734. * 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.
  41735. */
  41736. get: function () {
  41737. return this._shadowsSaturation;
  41738. },
  41739. /**
  41740. * Sets the shadows Saturation value.
  41741. * 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.
  41742. */
  41743. set: function (value) {
  41744. this._shadowsSaturation = value;
  41745. this._dirty = true;
  41746. },
  41747. enumerable: true,
  41748. configurable: true
  41749. });
  41750. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41751. /**
  41752. * Gets the shadows Exposure value.
  41753. * 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.
  41754. */
  41755. get: function () {
  41756. return this._shadowsExposure;
  41757. },
  41758. /**
  41759. * Sets the shadows Exposure value.
  41760. * 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.
  41761. */
  41762. set: function (value) {
  41763. this._shadowsExposure = value;
  41764. this._dirty = true;
  41765. },
  41766. enumerable: true,
  41767. configurable: true
  41768. });
  41769. ColorCurves.prototype.getClassName = function () {
  41770. return "ColorCurves";
  41771. };
  41772. /**
  41773. * Binds the color curves to the shader.
  41774. * @param colorCurves The color curve to bind
  41775. * @param effect The effect to bind to
  41776. */
  41777. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41778. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41779. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41780. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41781. if (colorCurves._dirty) {
  41782. colorCurves._dirty = false;
  41783. // Fill in global info.
  41784. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41785. // Compute highlights info.
  41786. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41787. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41788. // Compute midtones info.
  41789. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41790. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41791. // Compute shadows info.
  41792. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41793. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41794. // Compute deltas (neutral is midtones).
  41795. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41796. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41797. }
  41798. if (effect) {
  41799. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41800. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41801. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41802. }
  41803. };
  41804. /**
  41805. * Prepare the list of uniforms associated with the ColorCurves effects.
  41806. * @param uniformsList The list of uniforms used in the effect
  41807. */
  41808. ColorCurves.PrepareUniforms = function (uniformsList) {
  41809. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41810. };
  41811. /**
  41812. * Returns color grading data based on a hue, density, saturation and exposure value.
  41813. * @param filterHue The hue of the color filter.
  41814. * @param filterDensity The density of the color filter.
  41815. * @param saturation The saturation.
  41816. * @param exposure The exposure.
  41817. * @param result The result data container.
  41818. */
  41819. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41820. if (hue == null) {
  41821. return;
  41822. }
  41823. hue = ColorCurves.clamp(hue, 0, 360);
  41824. density = ColorCurves.clamp(density, -100, 100);
  41825. saturation = ColorCurves.clamp(saturation, -100, 100);
  41826. exposure = ColorCurves.clamp(exposure, -100, 100);
  41827. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41828. // so that the maximum filter density is only 50% control. This provides fine control
  41829. // for small values and reasonable range.
  41830. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41831. density *= 0.5;
  41832. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41833. if (density < 0) {
  41834. density *= -1;
  41835. hue = (hue + 180) % 360;
  41836. }
  41837. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41838. result.scaleToRef(2, result);
  41839. result.a = 1 + 0.01 * saturation;
  41840. };
  41841. /**
  41842. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41843. * @param value The input slider value in range [-100,100].
  41844. * @returns Adjusted value.
  41845. */
  41846. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41847. value /= 100;
  41848. var x = Math.abs(value);
  41849. x = Math.pow(x, 2);
  41850. if (value < 0) {
  41851. x *= -1;
  41852. }
  41853. x *= 100;
  41854. return x;
  41855. };
  41856. /**
  41857. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41858. * @param hue The hue (H) input.
  41859. * @param saturation The saturation (S) input.
  41860. * @param brightness The brightness (B) input.
  41861. * @result An RGBA color represented as Vector4.
  41862. */
  41863. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41864. var h = ColorCurves.clamp(hue, 0, 360);
  41865. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41866. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41867. if (s === 0) {
  41868. result.r = v;
  41869. result.g = v;
  41870. result.b = v;
  41871. }
  41872. else {
  41873. // sector 0 to 5
  41874. h /= 60;
  41875. var i = Math.floor(h);
  41876. // fractional part of h
  41877. var f = h - i;
  41878. var p = v * (1 - s);
  41879. var q = v * (1 - s * f);
  41880. var t = v * (1 - s * (1 - f));
  41881. switch (i) {
  41882. case 0:
  41883. result.r = v;
  41884. result.g = t;
  41885. result.b = p;
  41886. break;
  41887. case 1:
  41888. result.r = q;
  41889. result.g = v;
  41890. result.b = p;
  41891. break;
  41892. case 2:
  41893. result.r = p;
  41894. result.g = v;
  41895. result.b = t;
  41896. break;
  41897. case 3:
  41898. result.r = p;
  41899. result.g = q;
  41900. result.b = v;
  41901. break;
  41902. case 4:
  41903. result.r = t;
  41904. result.g = p;
  41905. result.b = v;
  41906. break;
  41907. default: // case 5:
  41908. result.r = v;
  41909. result.g = p;
  41910. result.b = q;
  41911. break;
  41912. }
  41913. }
  41914. result.a = 1;
  41915. };
  41916. /**
  41917. * Returns a value clamped between min and max
  41918. * @param value The value to clamp
  41919. * @param min The minimum of value
  41920. * @param max The maximum of value
  41921. * @returns The clamped value.
  41922. */
  41923. ColorCurves.clamp = function (value, min, max) {
  41924. return Math.min(Math.max(value, min), max);
  41925. };
  41926. /**
  41927. * Clones the current color curve instance.
  41928. * @return The cloned curves
  41929. */
  41930. ColorCurves.prototype.clone = function () {
  41931. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41932. };
  41933. /**
  41934. * Serializes the current color curve instance to a json representation.
  41935. * @return a JSON representation
  41936. */
  41937. ColorCurves.prototype.serialize = function () {
  41938. return BABYLON.SerializationHelper.Serialize(this);
  41939. };
  41940. /**
  41941. * Parses the color curve from a json representation.
  41942. * @param source the JSON source to parse
  41943. * @return The parsed curves
  41944. */
  41945. ColorCurves.Parse = function (source) {
  41946. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41947. };
  41948. __decorate([
  41949. BABYLON.serialize()
  41950. ], ColorCurves.prototype, "_globalHue", void 0);
  41951. __decorate([
  41952. BABYLON.serialize()
  41953. ], ColorCurves.prototype, "_globalDensity", void 0);
  41954. __decorate([
  41955. BABYLON.serialize()
  41956. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41957. __decorate([
  41958. BABYLON.serialize()
  41959. ], ColorCurves.prototype, "_globalExposure", void 0);
  41960. __decorate([
  41961. BABYLON.serialize()
  41962. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41963. __decorate([
  41964. BABYLON.serialize()
  41965. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41966. __decorate([
  41967. BABYLON.serialize()
  41968. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41969. __decorate([
  41970. BABYLON.serialize()
  41971. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41972. __decorate([
  41973. BABYLON.serialize()
  41974. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41975. __decorate([
  41976. BABYLON.serialize()
  41977. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41978. __decorate([
  41979. BABYLON.serialize()
  41980. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41981. __decorate([
  41982. BABYLON.serialize()
  41983. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41984. return ColorCurves;
  41985. }());
  41986. BABYLON.ColorCurves = ColorCurves;
  41987. })(BABYLON || (BABYLON = {}));
  41988. //# sourceMappingURL=babylon.colorCurves.js.map
  41989. //# sourceMappingURL=babylon.behavior.js.map
  41990. var BABYLON;
  41991. (function (BABYLON) {
  41992. /**
  41993. * "Static Class" containing the most commonly used helper while dealing with material for
  41994. * rendering purpose.
  41995. *
  41996. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41997. *
  41998. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41999. */
  42000. var MaterialHelper = /** @class */ (function () {
  42001. function MaterialHelper() {
  42002. }
  42003. /**
  42004. * Bind the current view position to an effect.
  42005. * @param effect The effect to be bound
  42006. * @param scene The scene the eyes position is used from
  42007. */
  42008. MaterialHelper.BindEyePosition = function (effect, scene) {
  42009. if (scene._forcedViewPosition) {
  42010. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42011. return;
  42012. }
  42013. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42014. };
  42015. /**
  42016. * Helps preparing the defines values about the UVs in used in the effect.
  42017. * UVs are shared as much as we can accross chanels in the shaders.
  42018. * @param texture The texture we are preparing the UVs for
  42019. * @param defines The defines to update
  42020. * @param key The chanel key "diffuse", "specular"... used in the shader
  42021. */
  42022. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42023. defines._needUVs = true;
  42024. defines[key] = true;
  42025. if (texture.getTextureMatrix().isIdentity(true)) {
  42026. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42027. if (texture.coordinatesIndex === 0) {
  42028. defines["MAINUV1"] = true;
  42029. }
  42030. else {
  42031. defines["MAINUV2"] = true;
  42032. }
  42033. }
  42034. else {
  42035. defines[key + "DIRECTUV"] = 0;
  42036. }
  42037. };
  42038. /**
  42039. * Binds a texture matrix value to its corrsponding uniform
  42040. * @param texture The texture to bind the matrix for
  42041. * @param uniformBuffer The uniform buffer receivin the data
  42042. * @param key The chanel key "diffuse", "specular"... used in the shader
  42043. */
  42044. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42045. var matrix = texture.getTextureMatrix();
  42046. if (!matrix.isIdentity(true)) {
  42047. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42048. }
  42049. };
  42050. /**
  42051. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42052. * @param mesh defines the current mesh
  42053. * @param scene defines the current scene
  42054. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42055. * @param pointsCloud defines if point cloud rendering has to be turned on
  42056. * @param fogEnabled defines if fog has to be turned on
  42057. * @param alphaTest defines if alpha testing has to be turned on
  42058. * @param defines defines the current list of defines
  42059. */
  42060. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42061. if (defines._areMiscDirty) {
  42062. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42063. defines["POINTSIZE"] = pointsCloud;
  42064. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42065. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42066. defines["ALPHATEST"] = alphaTest;
  42067. }
  42068. };
  42069. /**
  42070. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42071. * @param scene defines the current scene
  42072. * @param engine defines the current engine
  42073. * @param defines specifies the list of active defines
  42074. * @param useInstances defines if instances have to be turned on
  42075. * @param useClipPlane defines if clip plane have to be turned on
  42076. */
  42077. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42078. if (useClipPlane === void 0) { useClipPlane = null; }
  42079. var changed = false;
  42080. if (useClipPlane == null) {
  42081. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42082. }
  42083. if (defines["CLIPPLANE"] !== useClipPlane) {
  42084. defines["CLIPPLANE"] = useClipPlane;
  42085. changed = true;
  42086. }
  42087. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42088. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42089. changed = true;
  42090. }
  42091. if (defines["INSTANCES"] !== useInstances) {
  42092. defines["INSTANCES"] = useInstances;
  42093. changed = true;
  42094. }
  42095. if (changed) {
  42096. defines.markAsUnprocessed();
  42097. }
  42098. };
  42099. /**
  42100. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42101. * @param mesh The mesh containing the geometry data we will draw
  42102. * @param defines The defines to update
  42103. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42104. * @param useBones Precise whether bones should be used or not (override mesh info)
  42105. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42106. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42107. * @returns false if defines are considered not dirty and have not been checked
  42108. */
  42109. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42110. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42111. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42112. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42113. return false;
  42114. }
  42115. defines._normals = defines._needNormals;
  42116. defines._uvs = defines._needUVs;
  42117. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42118. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42119. defines["TANGENT"] = true;
  42120. }
  42121. if (defines._needUVs) {
  42122. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42123. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42124. }
  42125. else {
  42126. defines["UV1"] = false;
  42127. defines["UV2"] = false;
  42128. }
  42129. if (useVertexColor) {
  42130. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42131. defines["VERTEXCOLOR"] = hasVertexColors;
  42132. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42133. }
  42134. if (useBones) {
  42135. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42136. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42137. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42138. }
  42139. else {
  42140. defines["NUM_BONE_INFLUENCERS"] = 0;
  42141. defines["BonesPerMesh"] = 0;
  42142. }
  42143. }
  42144. if (useMorphTargets) {
  42145. var manager = mesh.morphTargetManager;
  42146. if (manager) {
  42147. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42148. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42149. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42150. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42151. }
  42152. else {
  42153. defines["MORPHTARGETS_TANGENT"] = false;
  42154. defines["MORPHTARGETS_NORMAL"] = false;
  42155. defines["MORPHTARGETS"] = false;
  42156. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42157. }
  42158. }
  42159. return true;
  42160. };
  42161. /**
  42162. * Prepares the defines related to the light information passed in parameter
  42163. * @param scene The scene we are intending to draw
  42164. * @param mesh The mesh the effect is compiling for
  42165. * @param defines The defines to update
  42166. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42167. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42168. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42169. * @returns true if normals will be required for the rest of the effect
  42170. */
  42171. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42172. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42173. if (disableLighting === void 0) { disableLighting = false; }
  42174. if (!defines._areLightsDirty) {
  42175. return defines._needNormals;
  42176. }
  42177. var lightIndex = 0;
  42178. var needNormals = false;
  42179. var needRebuild = false;
  42180. var lightmapMode = false;
  42181. var shadowEnabled = false;
  42182. var specularEnabled = false;
  42183. if (scene.lightsEnabled && !disableLighting) {
  42184. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42185. var light = _a[_i];
  42186. needNormals = true;
  42187. if (defines["LIGHT" + lightIndex] === undefined) {
  42188. needRebuild = true;
  42189. }
  42190. defines["LIGHT" + lightIndex] = true;
  42191. defines["SPOTLIGHT" + lightIndex] = false;
  42192. defines["HEMILIGHT" + lightIndex] = false;
  42193. defines["POINTLIGHT" + lightIndex] = false;
  42194. defines["DIRLIGHT" + lightIndex] = false;
  42195. var type;
  42196. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42197. type = "SPOTLIGHT" + lightIndex;
  42198. var spotLight = light;
  42199. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42200. }
  42201. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42202. type = "HEMILIGHT" + lightIndex;
  42203. }
  42204. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42205. type = "POINTLIGHT" + lightIndex;
  42206. }
  42207. else {
  42208. type = "DIRLIGHT" + lightIndex;
  42209. }
  42210. defines[type] = true;
  42211. // Specular
  42212. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42213. specularEnabled = true;
  42214. }
  42215. // Shadows
  42216. defines["SHADOW" + lightIndex] = false;
  42217. defines["SHADOWPCF" + lightIndex] = false;
  42218. defines["SHADOWPCSS" + lightIndex] = false;
  42219. defines["SHADOWPOISSON" + lightIndex] = false;
  42220. defines["SHADOWESM" + lightIndex] = false;
  42221. defines["SHADOWCUBE" + lightIndex] = false;
  42222. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42223. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42224. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42225. var shadowGenerator = light.getShadowGenerator();
  42226. if (shadowGenerator) {
  42227. shadowEnabled = true;
  42228. shadowGenerator.prepareDefines(defines, lightIndex);
  42229. }
  42230. }
  42231. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42232. lightmapMode = true;
  42233. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42234. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42235. }
  42236. else {
  42237. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42238. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42239. }
  42240. lightIndex++;
  42241. if (lightIndex === maxSimultaneousLights)
  42242. break;
  42243. }
  42244. }
  42245. defines["SPECULARTERM"] = specularEnabled;
  42246. defines["SHADOWS"] = shadowEnabled;
  42247. // Resetting all other lights if any
  42248. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42249. if (defines["LIGHT" + index] !== undefined) {
  42250. defines["LIGHT" + index] = false;
  42251. defines["HEMILIGHT" + lightIndex] = false;
  42252. defines["POINTLIGHT" + lightIndex] = false;
  42253. defines["DIRLIGHT" + lightIndex] = false;
  42254. defines["SPOTLIGHT" + lightIndex] = false;
  42255. defines["SHADOW" + lightIndex] = false;
  42256. }
  42257. }
  42258. var caps = scene.getEngine().getCaps();
  42259. if (defines["SHADOWFLOAT"] === undefined) {
  42260. needRebuild = true;
  42261. }
  42262. defines["SHADOWFLOAT"] = shadowEnabled &&
  42263. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42264. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42265. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42266. if (needRebuild) {
  42267. defines.rebuild();
  42268. }
  42269. return needNormals;
  42270. };
  42271. /**
  42272. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42273. * that won t be acctive due to defines being turned off.
  42274. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42275. * @param samplersList The samplers list
  42276. * @param defines The defines helping in the list generation
  42277. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42278. */
  42279. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42280. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42281. var uniformsList;
  42282. var uniformBuffersList = null;
  42283. if (uniformsListOrOptions.uniformsNames) {
  42284. var options = uniformsListOrOptions;
  42285. uniformsList = options.uniformsNames;
  42286. uniformBuffersList = options.uniformBuffersNames;
  42287. samplersList = options.samplers;
  42288. defines = options.defines;
  42289. maxSimultaneousLights = options.maxSimultaneousLights;
  42290. }
  42291. else {
  42292. uniformsList = uniformsListOrOptions;
  42293. if (!samplersList) {
  42294. samplersList = [];
  42295. }
  42296. }
  42297. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42298. if (!defines["LIGHT" + lightIndex]) {
  42299. break;
  42300. }
  42301. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42302. if (uniformBuffersList) {
  42303. uniformBuffersList.push("Light" + lightIndex);
  42304. }
  42305. samplersList.push("shadowSampler" + lightIndex);
  42306. samplersList.push("depthSampler" + lightIndex);
  42307. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42308. samplersList.push("projectionLightSampler" + lightIndex);
  42309. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42310. }
  42311. }
  42312. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42313. uniformsList.push("morphTargetInfluences");
  42314. }
  42315. };
  42316. /**
  42317. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42318. * @param defines The defines to update while falling back
  42319. * @param fallbacks The authorized effect fallbacks
  42320. * @param maxSimultaneousLights The maximum number of lights allowed
  42321. * @param rank the current rank of the Effect
  42322. * @returns The newly affected rank
  42323. */
  42324. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42325. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42326. if (rank === void 0) { rank = 0; }
  42327. var lightFallbackRank = 0;
  42328. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42329. if (!defines["LIGHT" + lightIndex]) {
  42330. break;
  42331. }
  42332. if (lightIndex > 0) {
  42333. lightFallbackRank = rank + lightIndex;
  42334. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42335. }
  42336. if (!defines["SHADOWS"]) {
  42337. if (defines["SHADOW" + lightIndex]) {
  42338. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42339. }
  42340. if (defines["SHADOWPCF" + lightIndex]) {
  42341. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42342. }
  42343. if (defines["SHADOWPCSS" + lightIndex]) {
  42344. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42345. }
  42346. if (defines["SHADOWPOISSON" + lightIndex]) {
  42347. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42348. }
  42349. if (defines["SHADOWESM" + lightIndex]) {
  42350. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42351. }
  42352. }
  42353. }
  42354. return lightFallbackRank++;
  42355. };
  42356. /**
  42357. * Prepares the list of attributes required for morph targets according to the effect defines.
  42358. * @param attribs The current list of supported attribs
  42359. * @param mesh The mesh to prepare the morph targets attributes for
  42360. * @param defines The current Defines of the effect
  42361. */
  42362. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42363. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42364. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42365. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42366. var manager = mesh.morphTargetManager;
  42367. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42368. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42369. for (var index = 0; index < influencers; index++) {
  42370. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42371. if (normal) {
  42372. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42373. }
  42374. if (tangent) {
  42375. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42376. }
  42377. if (attribs.length > maxAttributesCount) {
  42378. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42379. }
  42380. }
  42381. }
  42382. };
  42383. /**
  42384. * Prepares the list of attributes required for bones according to the effect defines.
  42385. * @param attribs The current list of supported attribs
  42386. * @param mesh The mesh to prepare the bones attributes for
  42387. * @param defines The current Defines of the effect
  42388. * @param fallbacks The current efffect fallback strategy
  42389. */
  42390. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42391. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42392. fallbacks.addCPUSkinningFallback(0, mesh);
  42393. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42394. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42395. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42396. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42397. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42398. }
  42399. }
  42400. };
  42401. /**
  42402. * Prepares the list of attributes required for instances according to the effect defines.
  42403. * @param attribs The current list of supported attribs
  42404. * @param defines The current Defines of the effect
  42405. */
  42406. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42407. if (defines["INSTANCES"]) {
  42408. attribs.push("world0");
  42409. attribs.push("world1");
  42410. attribs.push("world2");
  42411. attribs.push("world3");
  42412. }
  42413. };
  42414. /**
  42415. * Binds the light shadow information to the effect for the given mesh.
  42416. * @param light The light containing the generator
  42417. * @param scene The scene the lights belongs to
  42418. * @param mesh The mesh we are binding the information to render
  42419. * @param lightIndex The light index in the effect used to render the mesh
  42420. * @param effect The effect we are binding the data to
  42421. */
  42422. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42423. if (light.shadowEnabled && mesh.receiveShadows) {
  42424. var shadowGenerator = light.getShadowGenerator();
  42425. if (shadowGenerator) {
  42426. shadowGenerator.bindShadowLight(lightIndex, effect);
  42427. }
  42428. }
  42429. };
  42430. /**
  42431. * Binds the light information to the effect.
  42432. * @param light The light containing the generator
  42433. * @param effect The effect we are binding the data to
  42434. * @param lightIndex The light index in the effect used to render
  42435. */
  42436. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42437. light.transferToEffect(effect, lightIndex + "");
  42438. };
  42439. /**
  42440. * Binds the lights information from the scene to the effect for the given mesh.
  42441. * @param scene The scene the lights belongs to
  42442. * @param mesh The mesh we are binding the information to render
  42443. * @param effect The effect we are binding the data to
  42444. * @param defines The generated defines for the effect
  42445. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42446. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42447. */
  42448. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42449. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42450. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42451. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42452. for (var i = 0; i < len; i++) {
  42453. var light = mesh._lightSources[i];
  42454. var iAsString = i.toString();
  42455. var scaledIntensity = light.getScaledIntensity();
  42456. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42457. MaterialHelper.BindLightProperties(light, effect, i);
  42458. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42459. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42460. if (defines["SPECULARTERM"]) {
  42461. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42462. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42463. }
  42464. // Shadows
  42465. if (scene.shadowsEnabled) {
  42466. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42467. }
  42468. light._uniformBuffer.update();
  42469. }
  42470. };
  42471. /**
  42472. * Binds the fog information from the scene to the effect for the given mesh.
  42473. * @param scene The scene the lights belongs to
  42474. * @param mesh The mesh we are binding the information to render
  42475. * @param effect The effect we are binding the data to
  42476. */
  42477. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42478. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42479. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42480. effect.setColor3("vFogColor", scene.fogColor);
  42481. }
  42482. };
  42483. /**
  42484. * Binds the bones information from the mesh to the effect.
  42485. * @param mesh The mesh we are binding the information to render
  42486. * @param effect The effect we are binding the data to
  42487. */
  42488. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42489. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42490. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42491. if (matrices && effect) {
  42492. effect.setMatrices("mBones", matrices);
  42493. }
  42494. }
  42495. };
  42496. /**
  42497. * Binds the morph targets information from the mesh to the effect.
  42498. * @param abstractMesh The mesh we are binding the information to render
  42499. * @param effect The effect we are binding the data to
  42500. */
  42501. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42502. var manager = abstractMesh.morphTargetManager;
  42503. if (!abstractMesh || !manager) {
  42504. return;
  42505. }
  42506. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42507. };
  42508. /**
  42509. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42510. * @param defines The generated defines used in the effect
  42511. * @param effect The effect we are binding the data to
  42512. * @param scene The scene we are willing to render with logarithmic scale for
  42513. */
  42514. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42515. if (defines["LOGARITHMICDEPTH"]) {
  42516. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42517. }
  42518. };
  42519. /**
  42520. * Binds the clip plane information from the scene to the effect.
  42521. * @param scene The scene the clip plane information are extracted from
  42522. * @param effect The effect we are binding the data to
  42523. */
  42524. MaterialHelper.BindClipPlane = function (effect, scene) {
  42525. if (scene.clipPlane) {
  42526. var clipPlane = scene.clipPlane;
  42527. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42528. }
  42529. };
  42530. return MaterialHelper;
  42531. }());
  42532. BABYLON.MaterialHelper = MaterialHelper;
  42533. })(BABYLON || (BABYLON = {}));
  42534. //# sourceMappingURL=babylon.materialHelper.js.map
  42535. var BABYLON;
  42536. (function (BABYLON) {
  42537. var PushMaterial = /** @class */ (function (_super) {
  42538. __extends(PushMaterial, _super);
  42539. function PushMaterial(name, scene) {
  42540. var _this = _super.call(this, name, scene) || this;
  42541. _this._normalMatrix = new BABYLON.Matrix();
  42542. _this.storeEffectOnSubMeshes = true;
  42543. return _this;
  42544. }
  42545. PushMaterial.prototype.getEffect = function () {
  42546. return this._activeEffect;
  42547. };
  42548. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42549. if (!mesh) {
  42550. return false;
  42551. }
  42552. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42553. return true;
  42554. }
  42555. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42556. };
  42557. /**
  42558. * Binds the given world matrix to the active effect
  42559. *
  42560. * @param world the matrix to bind
  42561. */
  42562. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42563. this._activeEffect.setMatrix("world", world);
  42564. };
  42565. /**
  42566. * Binds the given normal matrix to the active effect
  42567. *
  42568. * @param normalMatrix the matrix to bind
  42569. */
  42570. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42571. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42572. };
  42573. PushMaterial.prototype.bind = function (world, mesh) {
  42574. if (!mesh) {
  42575. return;
  42576. }
  42577. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42578. };
  42579. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42580. if (effect === void 0) { effect = null; }
  42581. _super.prototype._afterBind.call(this, mesh);
  42582. this.getScene()._cachedEffect = effect;
  42583. };
  42584. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42585. if (visibility === void 0) { visibility = 1; }
  42586. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42587. };
  42588. return PushMaterial;
  42589. }(BABYLON.Material));
  42590. BABYLON.PushMaterial = PushMaterial;
  42591. })(BABYLON || (BABYLON = {}));
  42592. //# sourceMappingURL=babylon.pushMaterial.js.map
  42593. var BABYLON;
  42594. (function (BABYLON) {
  42595. /** @hidden */
  42596. var StandardMaterialDefines = /** @class */ (function (_super) {
  42597. __extends(StandardMaterialDefines, _super);
  42598. function StandardMaterialDefines() {
  42599. var _this = _super.call(this) || this;
  42600. _this.MAINUV1 = false;
  42601. _this.MAINUV2 = false;
  42602. _this.DIFFUSE = false;
  42603. _this.DIFFUSEDIRECTUV = 0;
  42604. _this.AMBIENT = false;
  42605. _this.AMBIENTDIRECTUV = 0;
  42606. _this.OPACITY = false;
  42607. _this.OPACITYDIRECTUV = 0;
  42608. _this.OPACITYRGB = false;
  42609. _this.REFLECTION = false;
  42610. _this.EMISSIVE = false;
  42611. _this.EMISSIVEDIRECTUV = 0;
  42612. _this.SPECULAR = false;
  42613. _this.SPECULARDIRECTUV = 0;
  42614. _this.BUMP = false;
  42615. _this.BUMPDIRECTUV = 0;
  42616. _this.PARALLAX = false;
  42617. _this.PARALLAXOCCLUSION = false;
  42618. _this.SPECULAROVERALPHA = false;
  42619. _this.CLIPPLANE = false;
  42620. _this.ALPHATEST = false;
  42621. _this.DEPTHPREPASS = false;
  42622. _this.ALPHAFROMDIFFUSE = false;
  42623. _this.POINTSIZE = false;
  42624. _this.FOG = false;
  42625. _this.SPECULARTERM = false;
  42626. _this.DIFFUSEFRESNEL = false;
  42627. _this.OPACITYFRESNEL = false;
  42628. _this.REFLECTIONFRESNEL = false;
  42629. _this.REFRACTIONFRESNEL = false;
  42630. _this.EMISSIVEFRESNEL = false;
  42631. _this.FRESNEL = false;
  42632. _this.NORMAL = false;
  42633. _this.UV1 = false;
  42634. _this.UV2 = false;
  42635. _this.VERTEXCOLOR = false;
  42636. _this.VERTEXALPHA = false;
  42637. _this.NUM_BONE_INFLUENCERS = 0;
  42638. _this.BonesPerMesh = 0;
  42639. _this.INSTANCES = false;
  42640. _this.GLOSSINESS = false;
  42641. _this.ROUGHNESS = false;
  42642. _this.EMISSIVEASILLUMINATION = false;
  42643. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42644. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42645. _this.LIGHTMAP = false;
  42646. _this.LIGHTMAPDIRECTUV = 0;
  42647. _this.OBJECTSPACE_NORMALMAP = false;
  42648. _this.USELIGHTMAPASSHADOWMAP = false;
  42649. _this.REFLECTIONMAP_3D = false;
  42650. _this.REFLECTIONMAP_SPHERICAL = false;
  42651. _this.REFLECTIONMAP_PLANAR = false;
  42652. _this.REFLECTIONMAP_CUBIC = false;
  42653. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42654. _this.REFLECTIONMAP_PROJECTION = false;
  42655. _this.REFLECTIONMAP_SKYBOX = false;
  42656. _this.REFLECTIONMAP_EXPLICIT = false;
  42657. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42658. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42659. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42660. _this.INVERTCUBICMAP = false;
  42661. _this.LOGARITHMICDEPTH = false;
  42662. _this.REFRACTION = false;
  42663. _this.REFRACTIONMAP_3D = false;
  42664. _this.REFLECTIONOVERALPHA = false;
  42665. _this.TWOSIDEDLIGHTING = false;
  42666. _this.SHADOWFLOAT = false;
  42667. _this.MORPHTARGETS = false;
  42668. _this.MORPHTARGETS_NORMAL = false;
  42669. _this.MORPHTARGETS_TANGENT = false;
  42670. _this.NUM_MORPH_INFLUENCERS = 0;
  42671. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42672. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42673. _this.IMAGEPROCESSING = false;
  42674. _this.VIGNETTE = false;
  42675. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42676. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42677. _this.TONEMAPPING = false;
  42678. _this.CONTRAST = false;
  42679. _this.COLORCURVES = false;
  42680. _this.COLORGRADING = false;
  42681. _this.COLORGRADING3D = false;
  42682. _this.SAMPLER3DGREENDEPTH = false;
  42683. _this.SAMPLER3DBGRMAP = false;
  42684. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42685. /**
  42686. * If the reflection texture on this material is in linear color space
  42687. * @hidden
  42688. */
  42689. _this.IS_REFLECTION_LINEAR = false;
  42690. /**
  42691. * If the refraction texture on this material is in linear color space
  42692. * @hidden
  42693. */
  42694. _this.IS_REFRACTION_LINEAR = false;
  42695. _this.EXPOSURE = false;
  42696. _this.rebuild();
  42697. return _this;
  42698. }
  42699. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42700. var modes = [
  42701. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42702. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42703. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42704. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42705. ];
  42706. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42707. var mode = modes_1[_i];
  42708. this[mode] = (mode === modeToEnable);
  42709. }
  42710. };
  42711. return StandardMaterialDefines;
  42712. }(BABYLON.MaterialDefines));
  42713. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42714. var StandardMaterial = /** @class */ (function (_super) {
  42715. __extends(StandardMaterial, _super);
  42716. function StandardMaterial(name, scene) {
  42717. var _this = _super.call(this, name, scene) || this;
  42718. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42719. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42720. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42721. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42722. _this.specularPower = 64;
  42723. _this._useAlphaFromDiffuseTexture = false;
  42724. _this._useEmissiveAsIllumination = false;
  42725. _this._linkEmissiveWithDiffuse = false;
  42726. _this._useSpecularOverAlpha = false;
  42727. _this._useReflectionOverAlpha = false;
  42728. _this._disableLighting = false;
  42729. _this._useObjectSpaceNormalMap = false;
  42730. _this._useParallax = false;
  42731. _this._useParallaxOcclusion = false;
  42732. _this.parallaxScaleBias = 0.05;
  42733. _this._roughness = 0;
  42734. _this.indexOfRefraction = 0.98;
  42735. _this.invertRefractionY = true;
  42736. /**
  42737. * Defines the alpha limits in alpha test mode
  42738. */
  42739. _this.alphaCutOff = 0.4;
  42740. _this._useLightmapAsShadowmap = false;
  42741. _this._useReflectionFresnelFromSpecular = false;
  42742. _this._useGlossinessFromSpecularMapAlpha = false;
  42743. _this._maxSimultaneousLights = 4;
  42744. /**
  42745. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42746. */
  42747. _this._invertNormalMapX = false;
  42748. /**
  42749. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42750. */
  42751. _this._invertNormalMapY = false;
  42752. /**
  42753. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42754. */
  42755. _this._twoSidedLighting = false;
  42756. _this._renderTargets = new BABYLON.SmartArray(16);
  42757. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42758. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42759. // Setup the default processing configuration to the scene.
  42760. _this._attachImageProcessingConfiguration(null);
  42761. _this.getRenderTargetTextures = function () {
  42762. _this._renderTargets.reset();
  42763. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42764. _this._renderTargets.push(_this._reflectionTexture);
  42765. }
  42766. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42767. _this._renderTargets.push(_this._refractionTexture);
  42768. }
  42769. return _this._renderTargets;
  42770. };
  42771. return _this;
  42772. }
  42773. ;
  42774. ;
  42775. ;
  42776. ;
  42777. ;
  42778. ;
  42779. ;
  42780. ;
  42781. ;
  42782. ;
  42783. ;
  42784. ;
  42785. ;
  42786. ;
  42787. ;
  42788. ;
  42789. ;
  42790. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42791. /**
  42792. * Gets the image processing configuration used either in this material.
  42793. */
  42794. get: function () {
  42795. return this._imageProcessingConfiguration;
  42796. },
  42797. /**
  42798. * Sets the Default image processing configuration used either in the this material.
  42799. *
  42800. * If sets to null, the scene one is in use.
  42801. */
  42802. set: function (value) {
  42803. this._attachImageProcessingConfiguration(value);
  42804. // Ensure the effect will be rebuilt.
  42805. this._markAllSubMeshesAsTexturesDirty();
  42806. },
  42807. enumerable: true,
  42808. configurable: true
  42809. });
  42810. /**
  42811. * Attaches a new image processing configuration to the Standard Material.
  42812. * @param configuration
  42813. */
  42814. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42815. var _this = this;
  42816. if (configuration === this._imageProcessingConfiguration) {
  42817. return;
  42818. }
  42819. // Detaches observer.
  42820. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42821. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42822. }
  42823. // Pick the scene configuration if needed.
  42824. if (!configuration) {
  42825. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42826. }
  42827. else {
  42828. this._imageProcessingConfiguration = configuration;
  42829. }
  42830. // Attaches observer.
  42831. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42832. _this._markAllSubMeshesAsImageProcessingDirty();
  42833. });
  42834. };
  42835. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42836. /**
  42837. * Gets wether the color curves effect is enabled.
  42838. */
  42839. get: function () {
  42840. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42841. },
  42842. /**
  42843. * Sets wether the color curves effect is enabled.
  42844. */
  42845. set: function (value) {
  42846. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42847. },
  42848. enumerable: true,
  42849. configurable: true
  42850. });
  42851. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42852. /**
  42853. * Gets wether the color grading effect is enabled.
  42854. */
  42855. get: function () {
  42856. return this.imageProcessingConfiguration.colorGradingEnabled;
  42857. },
  42858. /**
  42859. * Gets wether the color grading effect is enabled.
  42860. */
  42861. set: function (value) {
  42862. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42863. },
  42864. enumerable: true,
  42865. configurable: true
  42866. });
  42867. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42868. /**
  42869. * Gets wether tonemapping is enabled or not.
  42870. */
  42871. get: function () {
  42872. return this._imageProcessingConfiguration.toneMappingEnabled;
  42873. },
  42874. /**
  42875. * Sets wether tonemapping is enabled or not
  42876. */
  42877. set: function (value) {
  42878. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42879. },
  42880. enumerable: true,
  42881. configurable: true
  42882. });
  42883. ;
  42884. ;
  42885. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42886. /**
  42887. * The camera exposure used on this material.
  42888. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42889. * This corresponds to a photographic exposure.
  42890. */
  42891. get: function () {
  42892. return this._imageProcessingConfiguration.exposure;
  42893. },
  42894. /**
  42895. * The camera exposure used on this material.
  42896. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42897. * This corresponds to a photographic exposure.
  42898. */
  42899. set: function (value) {
  42900. this._imageProcessingConfiguration.exposure = value;
  42901. },
  42902. enumerable: true,
  42903. configurable: true
  42904. });
  42905. ;
  42906. ;
  42907. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42908. /**
  42909. * Gets The camera contrast used on this material.
  42910. */
  42911. get: function () {
  42912. return this._imageProcessingConfiguration.contrast;
  42913. },
  42914. /**
  42915. * Sets The camera contrast used on this material.
  42916. */
  42917. set: function (value) {
  42918. this._imageProcessingConfiguration.contrast = value;
  42919. },
  42920. enumerable: true,
  42921. configurable: true
  42922. });
  42923. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42924. /**
  42925. * Gets the Color Grading 2D Lookup Texture.
  42926. */
  42927. get: function () {
  42928. return this._imageProcessingConfiguration.colorGradingTexture;
  42929. },
  42930. /**
  42931. * Sets the Color Grading 2D Lookup Texture.
  42932. */
  42933. set: function (value) {
  42934. this._imageProcessingConfiguration.colorGradingTexture = value;
  42935. },
  42936. enumerable: true,
  42937. configurable: true
  42938. });
  42939. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42940. /**
  42941. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42942. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42943. * 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;
  42944. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42945. */
  42946. get: function () {
  42947. return this._imageProcessingConfiguration.colorCurves;
  42948. },
  42949. /**
  42950. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42951. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42952. * 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;
  42953. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42954. */
  42955. set: function (value) {
  42956. this._imageProcessingConfiguration.colorCurves = value;
  42957. },
  42958. enumerable: true,
  42959. configurable: true
  42960. });
  42961. StandardMaterial.prototype.getClassName = function () {
  42962. return "StandardMaterial";
  42963. };
  42964. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42965. get: function () {
  42966. return this._useLogarithmicDepth;
  42967. },
  42968. set: function (value) {
  42969. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42970. this._markAllSubMeshesAsMiscDirty();
  42971. },
  42972. enumerable: true,
  42973. configurable: true
  42974. });
  42975. StandardMaterial.prototype.needAlphaBlending = function () {
  42976. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42977. };
  42978. StandardMaterial.prototype.needAlphaTesting = function () {
  42979. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42980. };
  42981. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42982. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42983. };
  42984. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42985. return this._diffuseTexture;
  42986. };
  42987. /**
  42988. * Child classes can use it to update shaders
  42989. */
  42990. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42991. if (useInstances === void 0) { useInstances = false; }
  42992. if (subMesh.effect && this.isFrozen) {
  42993. if (this._wasPreviouslyReady && subMesh.effect) {
  42994. return true;
  42995. }
  42996. }
  42997. if (!subMesh._materialDefines) {
  42998. subMesh._materialDefines = new StandardMaterialDefines();
  42999. }
  43000. var scene = this.getScene();
  43001. var defines = subMesh._materialDefines;
  43002. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43003. if (defines._renderId === scene.getRenderId()) {
  43004. return true;
  43005. }
  43006. }
  43007. var engine = scene.getEngine();
  43008. // Lights
  43009. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43010. // Textures
  43011. if (defines._areTexturesDirty) {
  43012. defines._needUVs = false;
  43013. defines.MAINUV1 = false;
  43014. defines.MAINUV2 = false;
  43015. if (scene.texturesEnabled) {
  43016. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43017. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43018. return false;
  43019. }
  43020. else {
  43021. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43022. }
  43023. }
  43024. else {
  43025. defines.DIFFUSE = false;
  43026. }
  43027. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43028. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43029. return false;
  43030. }
  43031. else {
  43032. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43033. }
  43034. }
  43035. else {
  43036. defines.AMBIENT = false;
  43037. }
  43038. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43039. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43040. return false;
  43041. }
  43042. else {
  43043. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43044. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43045. }
  43046. }
  43047. else {
  43048. defines.OPACITY = false;
  43049. }
  43050. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43051. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43052. return false;
  43053. }
  43054. else {
  43055. defines._needNormals = true;
  43056. defines.REFLECTION = true;
  43057. defines.ROUGHNESS = (this._roughness > 0);
  43058. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43059. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43060. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43061. switch (this._reflectionTexture.coordinatesMode) {
  43062. case BABYLON.Texture.EXPLICIT_MODE:
  43063. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43064. break;
  43065. case BABYLON.Texture.PLANAR_MODE:
  43066. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43067. break;
  43068. case BABYLON.Texture.PROJECTION_MODE:
  43069. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43070. break;
  43071. case BABYLON.Texture.SKYBOX_MODE:
  43072. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43073. break;
  43074. case BABYLON.Texture.SPHERICAL_MODE:
  43075. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43076. break;
  43077. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43078. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43079. break;
  43080. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43081. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43082. break;
  43083. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43084. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43085. break;
  43086. case BABYLON.Texture.CUBIC_MODE:
  43087. case BABYLON.Texture.INVCUBIC_MODE:
  43088. default:
  43089. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43090. break;
  43091. }
  43092. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43093. }
  43094. }
  43095. else {
  43096. defines.REFLECTION = false;
  43097. }
  43098. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43099. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43100. return false;
  43101. }
  43102. else {
  43103. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43104. }
  43105. }
  43106. else {
  43107. defines.EMISSIVE = false;
  43108. }
  43109. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43110. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43111. return false;
  43112. }
  43113. else {
  43114. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43115. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43116. }
  43117. }
  43118. else {
  43119. defines.LIGHTMAP = false;
  43120. }
  43121. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43122. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43123. return false;
  43124. }
  43125. else {
  43126. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43127. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43128. }
  43129. }
  43130. else {
  43131. defines.SPECULAR = false;
  43132. }
  43133. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43134. // Bump texure can not be not blocking.
  43135. if (!this._bumpTexture.isReady()) {
  43136. return false;
  43137. }
  43138. else {
  43139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43140. defines.PARALLAX = this._useParallax;
  43141. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43142. }
  43143. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43144. }
  43145. else {
  43146. defines.BUMP = false;
  43147. }
  43148. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43149. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43150. return false;
  43151. }
  43152. else {
  43153. defines._needUVs = true;
  43154. defines.REFRACTION = true;
  43155. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43156. }
  43157. }
  43158. else {
  43159. defines.REFRACTION = false;
  43160. }
  43161. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43162. }
  43163. else {
  43164. defines.DIFFUSE = false;
  43165. defines.AMBIENT = false;
  43166. defines.OPACITY = false;
  43167. defines.REFLECTION = false;
  43168. defines.EMISSIVE = false;
  43169. defines.LIGHTMAP = false;
  43170. defines.BUMP = false;
  43171. defines.REFRACTION = false;
  43172. }
  43173. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43174. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43175. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43176. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43177. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43178. }
  43179. if (defines._areImageProcessingDirty) {
  43180. if (!this._imageProcessingConfiguration.isReady()) {
  43181. return false;
  43182. }
  43183. this._imageProcessingConfiguration.prepareDefines(defines);
  43184. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43185. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43186. }
  43187. if (defines._areFresnelDirty) {
  43188. if (StandardMaterial.FresnelEnabled) {
  43189. // Fresnel
  43190. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43191. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43192. this._reflectionFresnelParameters) {
  43193. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43194. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43195. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43196. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43197. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43198. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43199. defines._needNormals = true;
  43200. defines.FRESNEL = true;
  43201. }
  43202. }
  43203. else {
  43204. defines.FRESNEL = false;
  43205. }
  43206. }
  43207. // Misc.
  43208. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43209. // Attribs
  43210. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43211. // Values that need to be evaluated on every frame
  43212. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43213. // Get correct effect
  43214. if (defines.isDirty) {
  43215. defines.markAsProcessed();
  43216. scene.resetCachedMaterial();
  43217. // Fallbacks
  43218. var fallbacks = new BABYLON.EffectFallbacks();
  43219. if (defines.REFLECTION) {
  43220. fallbacks.addFallback(0, "REFLECTION");
  43221. }
  43222. if (defines.SPECULAR) {
  43223. fallbacks.addFallback(0, "SPECULAR");
  43224. }
  43225. if (defines.BUMP) {
  43226. fallbacks.addFallback(0, "BUMP");
  43227. }
  43228. if (defines.PARALLAX) {
  43229. fallbacks.addFallback(1, "PARALLAX");
  43230. }
  43231. if (defines.PARALLAXOCCLUSION) {
  43232. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43233. }
  43234. if (defines.SPECULAROVERALPHA) {
  43235. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43236. }
  43237. if (defines.FOG) {
  43238. fallbacks.addFallback(1, "FOG");
  43239. }
  43240. if (defines.POINTSIZE) {
  43241. fallbacks.addFallback(0, "POINTSIZE");
  43242. }
  43243. if (defines.LOGARITHMICDEPTH) {
  43244. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43245. }
  43246. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43247. if (defines.SPECULARTERM) {
  43248. fallbacks.addFallback(0, "SPECULARTERM");
  43249. }
  43250. if (defines.DIFFUSEFRESNEL) {
  43251. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43252. }
  43253. if (defines.OPACITYFRESNEL) {
  43254. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43255. }
  43256. if (defines.REFLECTIONFRESNEL) {
  43257. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43258. }
  43259. if (defines.EMISSIVEFRESNEL) {
  43260. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43261. }
  43262. if (defines.FRESNEL) {
  43263. fallbacks.addFallback(4, "FRESNEL");
  43264. }
  43265. //Attributes
  43266. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43267. if (defines.NORMAL) {
  43268. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43269. }
  43270. if (defines.UV1) {
  43271. attribs.push(BABYLON.VertexBuffer.UVKind);
  43272. }
  43273. if (defines.UV2) {
  43274. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43275. }
  43276. if (defines.VERTEXCOLOR) {
  43277. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43278. }
  43279. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43280. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43281. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43282. var shaderName = "default";
  43283. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43284. "vFogInfos", "vFogColor", "pointSize",
  43285. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43286. "mBones",
  43287. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43288. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43289. "vReflectionPosition", "vReflectionSize",
  43290. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43291. ];
  43292. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43293. var uniformBuffers = ["Material", "Scene"];
  43294. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43295. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43296. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43297. uniformsNames: uniforms,
  43298. uniformBuffersNames: uniformBuffers,
  43299. samplers: samplers,
  43300. defines: defines,
  43301. maxSimultaneousLights: this._maxSimultaneousLights
  43302. });
  43303. if (this.customShaderNameResolve) {
  43304. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43305. }
  43306. var join = defines.toString();
  43307. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43308. attributes: attribs,
  43309. uniformsNames: uniforms,
  43310. uniformBuffersNames: uniformBuffers,
  43311. samplers: samplers,
  43312. defines: join,
  43313. fallbacks: fallbacks,
  43314. onCompiled: this.onCompiled,
  43315. onError: this.onError,
  43316. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43317. }, engine), defines);
  43318. this.buildUniformLayout();
  43319. }
  43320. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43321. return false;
  43322. }
  43323. defines._renderId = scene.getRenderId();
  43324. this._wasPreviouslyReady = true;
  43325. return true;
  43326. };
  43327. StandardMaterial.prototype.buildUniformLayout = function () {
  43328. // Order is important !
  43329. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43330. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43331. this._uniformBuffer.addUniform("opacityParts", 4);
  43332. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43333. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43334. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43335. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43336. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43337. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43338. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43339. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43340. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43341. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43342. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43343. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43344. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43345. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43346. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43347. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43348. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43349. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43350. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43351. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43352. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43353. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43354. this._uniformBuffer.addUniform("specularMatrix", 16);
  43355. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43356. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43357. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43358. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43359. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43360. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43361. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43362. this._uniformBuffer.addUniform("pointSize", 1);
  43363. this._uniformBuffer.create();
  43364. };
  43365. StandardMaterial.prototype.unbind = function () {
  43366. if (this._activeEffect) {
  43367. var needFlag = false;
  43368. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43369. this._activeEffect.setTexture("reflection2DSampler", null);
  43370. needFlag = true;
  43371. }
  43372. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43373. this._activeEffect.setTexture("refraction2DSampler", null);
  43374. needFlag = true;
  43375. }
  43376. if (needFlag) {
  43377. this._markAllSubMeshesAsTexturesDirty();
  43378. }
  43379. }
  43380. _super.prototype.unbind.call(this);
  43381. };
  43382. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43383. var scene = this.getScene();
  43384. var defines = subMesh._materialDefines;
  43385. if (!defines) {
  43386. return;
  43387. }
  43388. var effect = subMesh.effect;
  43389. if (!effect) {
  43390. return;
  43391. }
  43392. this._activeEffect = effect;
  43393. // Matrices
  43394. this.bindOnlyWorldMatrix(world);
  43395. // Normal Matrix
  43396. if (defines.OBJECTSPACE_NORMALMAP) {
  43397. world.toNormalMatrix(this._normalMatrix);
  43398. this.bindOnlyNormalMatrix(this._normalMatrix);
  43399. }
  43400. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43401. // Bones
  43402. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43403. if (mustRebind) {
  43404. this._uniformBuffer.bindToEffect(effect, "Material");
  43405. this.bindViewProjection(effect);
  43406. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43407. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43408. // Fresnel
  43409. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43410. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43411. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43412. }
  43413. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43414. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43415. }
  43416. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43417. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43418. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43419. }
  43420. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43421. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43422. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43423. }
  43424. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43425. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43426. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43427. }
  43428. }
  43429. // Textures
  43430. if (scene.texturesEnabled) {
  43431. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43432. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43433. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43434. if (this._diffuseTexture.hasAlpha) {
  43435. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43436. }
  43437. }
  43438. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43439. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43440. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43441. }
  43442. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43443. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43444. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43445. }
  43446. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43447. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43448. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43449. if (this._reflectionTexture.boundingBoxSize) {
  43450. var cubeTexture = this._reflectionTexture;
  43451. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43452. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43453. }
  43454. }
  43455. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43456. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43457. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43458. }
  43459. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43460. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43461. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43462. }
  43463. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43464. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43465. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43466. }
  43467. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43468. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43469. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43470. if (scene._mirroredCameraPosition) {
  43471. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43472. }
  43473. else {
  43474. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43475. }
  43476. }
  43477. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43478. var depth = 1.0;
  43479. if (!this._refractionTexture.isCube) {
  43480. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43481. if (this._refractionTexture.depth) {
  43482. depth = this._refractionTexture.depth;
  43483. }
  43484. }
  43485. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43486. }
  43487. }
  43488. // Point size
  43489. if (this.pointsCloud) {
  43490. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43491. }
  43492. if (defines.SPECULARTERM) {
  43493. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43494. }
  43495. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43496. // Diffuse
  43497. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43498. }
  43499. // Textures
  43500. if (scene.texturesEnabled) {
  43501. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43502. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43503. }
  43504. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43505. effect.setTexture("ambientSampler", this._ambientTexture);
  43506. }
  43507. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43508. effect.setTexture("opacitySampler", this._opacityTexture);
  43509. }
  43510. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43511. if (this._reflectionTexture.isCube) {
  43512. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43513. }
  43514. else {
  43515. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43516. }
  43517. }
  43518. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43519. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43520. }
  43521. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43522. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43523. }
  43524. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43525. effect.setTexture("specularSampler", this._specularTexture);
  43526. }
  43527. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43528. effect.setTexture("bumpSampler", this._bumpTexture);
  43529. }
  43530. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43531. var depth = 1.0;
  43532. if (this._refractionTexture.isCube) {
  43533. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43534. }
  43535. else {
  43536. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43537. }
  43538. }
  43539. }
  43540. // Clip plane
  43541. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43542. // Colors
  43543. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43544. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43545. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43546. }
  43547. if (mustRebind || !this.isFrozen) {
  43548. // Lights
  43549. if (scene.lightsEnabled && !this._disableLighting) {
  43550. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43551. }
  43552. // View
  43553. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43554. this.bindView(effect);
  43555. }
  43556. // Fog
  43557. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43558. // Morph targets
  43559. if (defines.NUM_MORPH_INFLUENCERS) {
  43560. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43561. }
  43562. // Log. depth
  43563. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43564. // image processing
  43565. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43566. this._imageProcessingConfiguration.bind(this._activeEffect);
  43567. }
  43568. }
  43569. this._uniformBuffer.update();
  43570. this._afterBind(mesh, this._activeEffect);
  43571. };
  43572. StandardMaterial.prototype.getAnimatables = function () {
  43573. var results = [];
  43574. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43575. results.push(this._diffuseTexture);
  43576. }
  43577. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43578. results.push(this._ambientTexture);
  43579. }
  43580. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43581. results.push(this._opacityTexture);
  43582. }
  43583. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43584. results.push(this._reflectionTexture);
  43585. }
  43586. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43587. results.push(this._emissiveTexture);
  43588. }
  43589. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43590. results.push(this._specularTexture);
  43591. }
  43592. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43593. results.push(this._bumpTexture);
  43594. }
  43595. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43596. results.push(this._lightmapTexture);
  43597. }
  43598. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43599. results.push(this._refractionTexture);
  43600. }
  43601. return results;
  43602. };
  43603. StandardMaterial.prototype.getActiveTextures = function () {
  43604. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43605. if (this._diffuseTexture) {
  43606. activeTextures.push(this._diffuseTexture);
  43607. }
  43608. if (this._ambientTexture) {
  43609. activeTextures.push(this._ambientTexture);
  43610. }
  43611. if (this._opacityTexture) {
  43612. activeTextures.push(this._opacityTexture);
  43613. }
  43614. if (this._reflectionTexture) {
  43615. activeTextures.push(this._reflectionTexture);
  43616. }
  43617. if (this._emissiveTexture) {
  43618. activeTextures.push(this._emissiveTexture);
  43619. }
  43620. if (this._specularTexture) {
  43621. activeTextures.push(this._specularTexture);
  43622. }
  43623. if (this._bumpTexture) {
  43624. activeTextures.push(this._bumpTexture);
  43625. }
  43626. if (this._lightmapTexture) {
  43627. activeTextures.push(this._lightmapTexture);
  43628. }
  43629. if (this._refractionTexture) {
  43630. activeTextures.push(this._refractionTexture);
  43631. }
  43632. return activeTextures;
  43633. };
  43634. StandardMaterial.prototype.hasTexture = function (texture) {
  43635. if (_super.prototype.hasTexture.call(this, texture)) {
  43636. return true;
  43637. }
  43638. if (this._diffuseTexture === texture) {
  43639. return true;
  43640. }
  43641. if (this._ambientTexture === texture) {
  43642. return true;
  43643. }
  43644. if (this._opacityTexture === texture) {
  43645. return true;
  43646. }
  43647. if (this._reflectionTexture === texture) {
  43648. return true;
  43649. }
  43650. if (this._emissiveTexture === texture) {
  43651. return true;
  43652. }
  43653. if (this._specularTexture === texture) {
  43654. return true;
  43655. }
  43656. if (this._bumpTexture === texture) {
  43657. return true;
  43658. }
  43659. if (this._lightmapTexture === texture) {
  43660. return true;
  43661. }
  43662. if (this._refractionTexture === texture) {
  43663. return true;
  43664. }
  43665. return false;
  43666. };
  43667. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43668. if (forceDisposeTextures) {
  43669. if (this._diffuseTexture) {
  43670. this._diffuseTexture.dispose();
  43671. }
  43672. if (this._ambientTexture) {
  43673. this._ambientTexture.dispose();
  43674. }
  43675. if (this._opacityTexture) {
  43676. this._opacityTexture.dispose();
  43677. }
  43678. if (this._reflectionTexture) {
  43679. this._reflectionTexture.dispose();
  43680. }
  43681. if (this._emissiveTexture) {
  43682. this._emissiveTexture.dispose();
  43683. }
  43684. if (this._specularTexture) {
  43685. this._specularTexture.dispose();
  43686. }
  43687. if (this._bumpTexture) {
  43688. this._bumpTexture.dispose();
  43689. }
  43690. if (this._lightmapTexture) {
  43691. this._lightmapTexture.dispose();
  43692. }
  43693. if (this._refractionTexture) {
  43694. this._refractionTexture.dispose();
  43695. }
  43696. }
  43697. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43698. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43699. }
  43700. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43701. };
  43702. StandardMaterial.prototype.clone = function (name) {
  43703. var _this = this;
  43704. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43705. result.name = name;
  43706. result.id = name;
  43707. return result;
  43708. };
  43709. StandardMaterial.prototype.serialize = function () {
  43710. return BABYLON.SerializationHelper.Serialize(this);
  43711. };
  43712. // Statics
  43713. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43714. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43715. };
  43716. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43717. get: function () {
  43718. return StandardMaterial._DiffuseTextureEnabled;
  43719. },
  43720. set: function (value) {
  43721. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43722. return;
  43723. }
  43724. StandardMaterial._DiffuseTextureEnabled = value;
  43725. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43726. },
  43727. enumerable: true,
  43728. configurable: true
  43729. });
  43730. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43731. get: function () {
  43732. return StandardMaterial._AmbientTextureEnabled;
  43733. },
  43734. set: function (value) {
  43735. if (StandardMaterial._AmbientTextureEnabled === value) {
  43736. return;
  43737. }
  43738. StandardMaterial._AmbientTextureEnabled = value;
  43739. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43740. },
  43741. enumerable: true,
  43742. configurable: true
  43743. });
  43744. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43745. get: function () {
  43746. return StandardMaterial._OpacityTextureEnabled;
  43747. },
  43748. set: function (value) {
  43749. if (StandardMaterial._OpacityTextureEnabled === value) {
  43750. return;
  43751. }
  43752. StandardMaterial._OpacityTextureEnabled = value;
  43753. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43754. },
  43755. enumerable: true,
  43756. configurable: true
  43757. });
  43758. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43759. get: function () {
  43760. return StandardMaterial._ReflectionTextureEnabled;
  43761. },
  43762. set: function (value) {
  43763. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43764. return;
  43765. }
  43766. StandardMaterial._ReflectionTextureEnabled = value;
  43767. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43768. },
  43769. enumerable: true,
  43770. configurable: true
  43771. });
  43772. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43773. get: function () {
  43774. return StandardMaterial._EmissiveTextureEnabled;
  43775. },
  43776. set: function (value) {
  43777. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43778. return;
  43779. }
  43780. StandardMaterial._EmissiveTextureEnabled = value;
  43781. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43782. },
  43783. enumerable: true,
  43784. configurable: true
  43785. });
  43786. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43787. get: function () {
  43788. return StandardMaterial._SpecularTextureEnabled;
  43789. },
  43790. set: function (value) {
  43791. if (StandardMaterial._SpecularTextureEnabled === value) {
  43792. return;
  43793. }
  43794. StandardMaterial._SpecularTextureEnabled = value;
  43795. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43796. },
  43797. enumerable: true,
  43798. configurable: true
  43799. });
  43800. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43801. get: function () {
  43802. return StandardMaterial._BumpTextureEnabled;
  43803. },
  43804. set: function (value) {
  43805. if (StandardMaterial._BumpTextureEnabled === value) {
  43806. return;
  43807. }
  43808. StandardMaterial._BumpTextureEnabled = value;
  43809. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43810. },
  43811. enumerable: true,
  43812. configurable: true
  43813. });
  43814. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43815. get: function () {
  43816. return StandardMaterial._LightmapTextureEnabled;
  43817. },
  43818. set: function (value) {
  43819. if (StandardMaterial._LightmapTextureEnabled === value) {
  43820. return;
  43821. }
  43822. StandardMaterial._LightmapTextureEnabled = value;
  43823. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43824. },
  43825. enumerable: true,
  43826. configurable: true
  43827. });
  43828. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43829. get: function () {
  43830. return StandardMaterial._RefractionTextureEnabled;
  43831. },
  43832. set: function (value) {
  43833. if (StandardMaterial._RefractionTextureEnabled === value) {
  43834. return;
  43835. }
  43836. StandardMaterial._RefractionTextureEnabled = value;
  43837. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43838. },
  43839. enumerable: true,
  43840. configurable: true
  43841. });
  43842. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43843. get: function () {
  43844. return StandardMaterial._ColorGradingTextureEnabled;
  43845. },
  43846. set: function (value) {
  43847. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43848. return;
  43849. }
  43850. StandardMaterial._ColorGradingTextureEnabled = value;
  43851. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43852. },
  43853. enumerable: true,
  43854. configurable: true
  43855. });
  43856. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43857. get: function () {
  43858. return StandardMaterial._FresnelEnabled;
  43859. },
  43860. set: function (value) {
  43861. if (StandardMaterial._FresnelEnabled === value) {
  43862. return;
  43863. }
  43864. StandardMaterial._FresnelEnabled = value;
  43865. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43866. },
  43867. enumerable: true,
  43868. configurable: true
  43869. });
  43870. // Flags used to enable or disable a type of texture for all Standard Materials
  43871. StandardMaterial._DiffuseTextureEnabled = true;
  43872. StandardMaterial._AmbientTextureEnabled = true;
  43873. StandardMaterial._OpacityTextureEnabled = true;
  43874. StandardMaterial._ReflectionTextureEnabled = true;
  43875. StandardMaterial._EmissiveTextureEnabled = true;
  43876. StandardMaterial._SpecularTextureEnabled = true;
  43877. StandardMaterial._BumpTextureEnabled = true;
  43878. StandardMaterial._LightmapTextureEnabled = true;
  43879. StandardMaterial._RefractionTextureEnabled = true;
  43880. StandardMaterial._ColorGradingTextureEnabled = true;
  43881. StandardMaterial._FresnelEnabled = true;
  43882. __decorate([
  43883. BABYLON.serializeAsTexture("diffuseTexture")
  43884. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43885. __decorate([
  43886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43887. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43888. __decorate([
  43889. BABYLON.serializeAsTexture("ambientTexture")
  43890. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43891. __decorate([
  43892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43893. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43894. __decorate([
  43895. BABYLON.serializeAsTexture("opacityTexture")
  43896. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43897. __decorate([
  43898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43899. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43900. __decorate([
  43901. BABYLON.serializeAsTexture("reflectionTexture")
  43902. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43903. __decorate([
  43904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43905. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43906. __decorate([
  43907. BABYLON.serializeAsTexture("emissiveTexture")
  43908. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43909. __decorate([
  43910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43911. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43912. __decorate([
  43913. BABYLON.serializeAsTexture("specularTexture")
  43914. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43915. __decorate([
  43916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43917. ], StandardMaterial.prototype, "specularTexture", void 0);
  43918. __decorate([
  43919. BABYLON.serializeAsTexture("bumpTexture")
  43920. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43921. __decorate([
  43922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43923. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43924. __decorate([
  43925. BABYLON.serializeAsTexture("lightmapTexture")
  43926. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43927. __decorate([
  43928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43929. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43930. __decorate([
  43931. BABYLON.serializeAsTexture("refractionTexture")
  43932. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43933. __decorate([
  43934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43935. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43936. __decorate([
  43937. BABYLON.serializeAsColor3("ambient")
  43938. ], StandardMaterial.prototype, "ambientColor", void 0);
  43939. __decorate([
  43940. BABYLON.serializeAsColor3("diffuse")
  43941. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43942. __decorate([
  43943. BABYLON.serializeAsColor3("specular")
  43944. ], StandardMaterial.prototype, "specularColor", void 0);
  43945. __decorate([
  43946. BABYLON.serializeAsColor3("emissive")
  43947. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43948. __decorate([
  43949. BABYLON.serialize()
  43950. ], StandardMaterial.prototype, "specularPower", void 0);
  43951. __decorate([
  43952. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43953. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43954. __decorate([
  43955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43956. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43957. __decorate([
  43958. BABYLON.serialize("useEmissiveAsIllumination")
  43959. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43960. __decorate([
  43961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43962. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43963. __decorate([
  43964. BABYLON.serialize("linkEmissiveWithDiffuse")
  43965. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43966. __decorate([
  43967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43968. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43969. __decorate([
  43970. BABYLON.serialize("useSpecularOverAlpha")
  43971. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43972. __decorate([
  43973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43974. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43975. __decorate([
  43976. BABYLON.serialize("useReflectionOverAlpha")
  43977. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43978. __decorate([
  43979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43980. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43981. __decorate([
  43982. BABYLON.serialize("disableLighting")
  43983. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43984. __decorate([
  43985. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43986. ], StandardMaterial.prototype, "disableLighting", void 0);
  43987. __decorate([
  43988. BABYLON.serialize("useObjectSpaceNormalMap")
  43989. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43990. __decorate([
  43991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43992. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43993. __decorate([
  43994. BABYLON.serialize("useParallax")
  43995. ], StandardMaterial.prototype, "_useParallax", void 0);
  43996. __decorate([
  43997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43998. ], StandardMaterial.prototype, "useParallax", void 0);
  43999. __decorate([
  44000. BABYLON.serialize("useParallaxOcclusion")
  44001. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44002. __decorate([
  44003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44004. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44005. __decorate([
  44006. BABYLON.serialize()
  44007. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44008. __decorate([
  44009. BABYLON.serialize("roughness")
  44010. ], StandardMaterial.prototype, "_roughness", void 0);
  44011. __decorate([
  44012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44013. ], StandardMaterial.prototype, "roughness", void 0);
  44014. __decorate([
  44015. BABYLON.serialize()
  44016. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44017. __decorate([
  44018. BABYLON.serialize()
  44019. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44020. __decorate([
  44021. BABYLON.serialize()
  44022. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44023. __decorate([
  44024. BABYLON.serialize("useLightmapAsShadowmap")
  44025. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44026. __decorate([
  44027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44028. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44029. __decorate([
  44030. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44031. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44032. __decorate([
  44033. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44034. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44035. __decorate([
  44036. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44037. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44038. __decorate([
  44039. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44040. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44041. __decorate([
  44042. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44043. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44044. __decorate([
  44045. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44046. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44047. __decorate([
  44048. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44049. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44050. __decorate([
  44051. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44052. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44053. __decorate([
  44054. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44055. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44056. __decorate([
  44057. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44058. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44059. __decorate([
  44060. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44061. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44062. __decorate([
  44063. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44064. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44065. __decorate([
  44066. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44067. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44068. __decorate([
  44069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44070. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44071. __decorate([
  44072. BABYLON.serialize("maxSimultaneousLights")
  44073. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44074. __decorate([
  44075. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44076. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44077. __decorate([
  44078. BABYLON.serialize("invertNormalMapX")
  44079. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44080. __decorate([
  44081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44082. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44083. __decorate([
  44084. BABYLON.serialize("invertNormalMapY")
  44085. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44086. __decorate([
  44087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44088. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44089. __decorate([
  44090. BABYLON.serialize("twoSidedLighting")
  44091. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44092. __decorate([
  44093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44094. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44095. __decorate([
  44096. BABYLON.serialize()
  44097. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44098. return StandardMaterial;
  44099. }(BABYLON.PushMaterial));
  44100. BABYLON.StandardMaterial = StandardMaterial;
  44101. })(BABYLON || (BABYLON = {}));
  44102. //# sourceMappingURL=babylon.standardMaterial.js.map
  44103. var BABYLON;
  44104. (function (BABYLON) {
  44105. /**
  44106. * Manages the defines for the PBR Material.
  44107. * @hiddenChildren
  44108. */
  44109. var PBRMaterialDefines = /** @class */ (function (_super) {
  44110. __extends(PBRMaterialDefines, _super);
  44111. /**
  44112. * Initializes the PBR Material defines.
  44113. */
  44114. function PBRMaterialDefines() {
  44115. var _this = _super.call(this) || this;
  44116. _this.PBR = true;
  44117. _this.MAINUV1 = false;
  44118. _this.MAINUV2 = false;
  44119. _this.UV1 = false;
  44120. _this.UV2 = false;
  44121. _this.ALBEDO = false;
  44122. _this.ALBEDODIRECTUV = 0;
  44123. _this.VERTEXCOLOR = false;
  44124. _this.AMBIENT = false;
  44125. _this.AMBIENTDIRECTUV = 0;
  44126. _this.AMBIENTINGRAYSCALE = false;
  44127. _this.OPACITY = false;
  44128. _this.VERTEXALPHA = false;
  44129. _this.OPACITYDIRECTUV = 0;
  44130. _this.OPACITYRGB = false;
  44131. _this.ALPHATEST = false;
  44132. _this.DEPTHPREPASS = false;
  44133. _this.ALPHABLEND = false;
  44134. _this.ALPHAFROMALBEDO = false;
  44135. _this.ALPHATESTVALUE = "0.5";
  44136. _this.SPECULAROVERALPHA = false;
  44137. _this.RADIANCEOVERALPHA = false;
  44138. _this.ALPHAFRESNEL = false;
  44139. _this.LINEARALPHAFRESNEL = false;
  44140. _this.PREMULTIPLYALPHA = false;
  44141. _this.EMISSIVE = false;
  44142. _this.EMISSIVEDIRECTUV = 0;
  44143. _this.REFLECTIVITY = false;
  44144. _this.REFLECTIVITYDIRECTUV = 0;
  44145. _this.SPECULARTERM = false;
  44146. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44147. _this.MICROSURFACEAUTOMATIC = false;
  44148. _this.LODBASEDMICROSFURACE = false;
  44149. _this.MICROSURFACEMAP = false;
  44150. _this.MICROSURFACEMAPDIRECTUV = 0;
  44151. _this.METALLICWORKFLOW = false;
  44152. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44153. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44154. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44155. _this.AOSTOREINMETALMAPRED = false;
  44156. _this.ENVIRONMENTBRDF = false;
  44157. _this.NORMAL = false;
  44158. _this.TANGENT = false;
  44159. _this.BUMP = false;
  44160. _this.BUMPDIRECTUV = 0;
  44161. _this.OBJECTSPACE_NORMALMAP = false;
  44162. _this.PARALLAX = false;
  44163. _this.PARALLAXOCCLUSION = false;
  44164. _this.NORMALXYSCALE = true;
  44165. _this.LIGHTMAP = false;
  44166. _this.LIGHTMAPDIRECTUV = 0;
  44167. _this.USELIGHTMAPASSHADOWMAP = false;
  44168. _this.GAMMALIGHTMAP = false;
  44169. _this.REFLECTION = false;
  44170. _this.REFLECTIONMAP_3D = false;
  44171. _this.REFLECTIONMAP_SPHERICAL = false;
  44172. _this.REFLECTIONMAP_PLANAR = false;
  44173. _this.REFLECTIONMAP_CUBIC = false;
  44174. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44175. _this.REFLECTIONMAP_PROJECTION = false;
  44176. _this.REFLECTIONMAP_SKYBOX = false;
  44177. _this.REFLECTIONMAP_EXPLICIT = false;
  44178. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44179. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44180. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44181. _this.INVERTCUBICMAP = false;
  44182. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44183. _this.USESPHERICALINVERTEX = false;
  44184. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44185. _this.LODINREFLECTIONALPHA = false;
  44186. _this.GAMMAREFLECTION = false;
  44187. _this.RADIANCEOCCLUSION = false;
  44188. _this.HORIZONOCCLUSION = false;
  44189. _this.REFRACTION = false;
  44190. _this.REFRACTIONMAP_3D = false;
  44191. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44192. _this.LODINREFRACTIONALPHA = false;
  44193. _this.GAMMAREFRACTION = false;
  44194. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44195. _this.INSTANCES = false;
  44196. _this.NUM_BONE_INFLUENCERS = 0;
  44197. _this.BonesPerMesh = 0;
  44198. _this.NONUNIFORMSCALING = false;
  44199. _this.MORPHTARGETS = false;
  44200. _this.MORPHTARGETS_NORMAL = false;
  44201. _this.MORPHTARGETS_TANGENT = false;
  44202. _this.NUM_MORPH_INFLUENCERS = 0;
  44203. _this.IMAGEPROCESSING = false;
  44204. _this.VIGNETTE = false;
  44205. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44206. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44207. _this.TONEMAPPING = false;
  44208. _this.CONTRAST = false;
  44209. _this.COLORCURVES = false;
  44210. _this.COLORGRADING = false;
  44211. _this.COLORGRADING3D = false;
  44212. _this.SAMPLER3DGREENDEPTH = false;
  44213. _this.SAMPLER3DBGRMAP = false;
  44214. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44215. _this.EXPOSURE = false;
  44216. _this.USEPHYSICALLIGHTFALLOFF = false;
  44217. _this.TWOSIDEDLIGHTING = false;
  44218. _this.SHADOWFLOAT = false;
  44219. _this.CLIPPLANE = false;
  44220. _this.POINTSIZE = false;
  44221. _this.FOG = false;
  44222. _this.LOGARITHMICDEPTH = false;
  44223. _this.FORCENORMALFORWARD = false;
  44224. _this.SPECULARAA = false;
  44225. _this.UNLIT = false;
  44226. _this.rebuild();
  44227. return _this;
  44228. }
  44229. /**
  44230. * Resets the PBR Material defines.
  44231. */
  44232. PBRMaterialDefines.prototype.reset = function () {
  44233. _super.prototype.reset.call(this);
  44234. this.ALPHATESTVALUE = "0.5";
  44235. this.PBR = true;
  44236. };
  44237. return PBRMaterialDefines;
  44238. }(BABYLON.MaterialDefines));
  44239. /**
  44240. * The Physically based material base class of BJS.
  44241. *
  44242. * This offers the main features of a standard PBR material.
  44243. * For more information, please refer to the documentation :
  44244. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44245. */
  44246. var PBRBaseMaterial = /** @class */ (function (_super) {
  44247. __extends(PBRBaseMaterial, _super);
  44248. /**
  44249. * Instantiates a new PBRMaterial instance.
  44250. *
  44251. * @param name The material name
  44252. * @param scene The scene the material will be use in.
  44253. */
  44254. function PBRBaseMaterial(name, scene) {
  44255. var _this = _super.call(this, name, scene) || this;
  44256. /**
  44257. * Intensity of the direct lights e.g. the four lights available in your scene.
  44258. * This impacts both the direct diffuse and specular highlights.
  44259. */
  44260. _this._directIntensity = 1.0;
  44261. /**
  44262. * Intensity of the emissive part of the material.
  44263. * This helps controlling the emissive effect without modifying the emissive color.
  44264. */
  44265. _this._emissiveIntensity = 1.0;
  44266. /**
  44267. * Intensity of the environment e.g. how much the environment will light the object
  44268. * either through harmonics for rough material or through the refelction for shiny ones.
  44269. */
  44270. _this._environmentIntensity = 1.0;
  44271. /**
  44272. * This is a special control allowing the reduction of the specular highlights coming from the
  44273. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44274. */
  44275. _this._specularIntensity = 1.0;
  44276. /**
  44277. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44278. */
  44279. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44280. /**
  44281. * Debug Control allowing disabling the bump map on this material.
  44282. */
  44283. _this._disableBumpMap = false;
  44284. /**
  44285. * AKA Occlusion Texture Intensity in other nomenclature.
  44286. */
  44287. _this._ambientTextureStrength = 1.0;
  44288. /**
  44289. * The color of a material in ambient lighting.
  44290. */
  44291. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44292. /**
  44293. * AKA Diffuse Color in other nomenclature.
  44294. */
  44295. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44296. /**
  44297. * AKA Specular Color in other nomenclature.
  44298. */
  44299. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44300. /**
  44301. * The color applied when light is reflected from a material.
  44302. */
  44303. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44304. /**
  44305. * The color applied when light is emitted from a material.
  44306. */
  44307. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44308. /**
  44309. * AKA Glossiness in other nomenclature.
  44310. */
  44311. _this._microSurface = 0.9;
  44312. /**
  44313. * source material index of refraction (IOR)' / 'destination material IOR.
  44314. */
  44315. _this._indexOfRefraction = 0.66;
  44316. /**
  44317. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44318. */
  44319. _this._invertRefractionY = false;
  44320. /**
  44321. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44322. * Materials half opaque for instance using refraction could benefit from this control.
  44323. */
  44324. _this._linkRefractionWithTransparency = false;
  44325. /**
  44326. * Specifies that the material will use the light map as a show map.
  44327. */
  44328. _this._useLightmapAsShadowmap = false;
  44329. /**
  44330. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44331. * makes the reflect vector face the model (under horizon).
  44332. */
  44333. _this._useHorizonOcclusion = true;
  44334. /**
  44335. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44336. * too much the area relying on ambient texture to define their ambient occlusion.
  44337. */
  44338. _this._useRadianceOcclusion = true;
  44339. /**
  44340. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44341. */
  44342. _this._useAlphaFromAlbedoTexture = false;
  44343. /**
  44344. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44345. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44346. */
  44347. _this._useSpecularOverAlpha = true;
  44348. /**
  44349. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44350. */
  44351. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44352. /**
  44353. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44354. */
  44355. _this._useRoughnessFromMetallicTextureAlpha = true;
  44356. /**
  44357. * Specifies if the metallic texture contains the roughness information in its green channel.
  44358. */
  44359. _this._useRoughnessFromMetallicTextureGreen = false;
  44360. /**
  44361. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44362. */
  44363. _this._useMetallnessFromMetallicTextureBlue = false;
  44364. /**
  44365. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44366. */
  44367. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44368. /**
  44369. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44370. */
  44371. _this._useAmbientInGrayScale = false;
  44372. /**
  44373. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44374. * The material will try to infer what glossiness each pixel should be.
  44375. */
  44376. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44377. /**
  44378. * BJS is using an harcoded light falloff based on a manually sets up range.
  44379. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44380. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44381. */
  44382. _this._usePhysicalLightFalloff = true;
  44383. /**
  44384. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44385. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44386. */
  44387. _this._useRadianceOverAlpha = true;
  44388. /**
  44389. * Allows using an object space normal map (instead of tangent space).
  44390. */
  44391. _this._useObjectSpaceNormalMap = false;
  44392. /**
  44393. * Allows using the bump map in parallax mode.
  44394. */
  44395. _this._useParallax = false;
  44396. /**
  44397. * Allows using the bump map in parallax occlusion mode.
  44398. */
  44399. _this._useParallaxOcclusion = false;
  44400. /**
  44401. * Controls the scale bias of the parallax mode.
  44402. */
  44403. _this._parallaxScaleBias = 0.05;
  44404. /**
  44405. * If sets to true, disables all the lights affecting the material.
  44406. */
  44407. _this._disableLighting = false;
  44408. /**
  44409. * Number of Simultaneous lights allowed on the material.
  44410. */
  44411. _this._maxSimultaneousLights = 4;
  44412. /**
  44413. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44414. */
  44415. _this._invertNormalMapX = false;
  44416. /**
  44417. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44418. */
  44419. _this._invertNormalMapY = false;
  44420. /**
  44421. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44422. */
  44423. _this._twoSidedLighting = false;
  44424. /**
  44425. * Defines the alpha limits in alpha test mode.
  44426. */
  44427. _this._alphaCutOff = 0.4;
  44428. /**
  44429. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44430. */
  44431. _this._forceAlphaTest = false;
  44432. /**
  44433. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44434. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44435. */
  44436. _this._useAlphaFresnel = false;
  44437. /**
  44438. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44439. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44440. */
  44441. _this._useLinearAlphaFresnel = false;
  44442. /**
  44443. * The transparency mode of the material.
  44444. */
  44445. _this._transparencyMode = null;
  44446. /**
  44447. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44448. * from cos thetav and roughness:
  44449. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44450. */
  44451. _this._environmentBRDFTexture = null;
  44452. /**
  44453. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44454. */
  44455. _this._forceIrradianceInFragment = false;
  44456. /**
  44457. * Force normal to face away from face.
  44458. */
  44459. _this._forceNormalForward = false;
  44460. /**
  44461. * Enables specular anti aliasing in the PBR shader.
  44462. * It will both interacts on the Geometry for analytical and IBL lighting.
  44463. * It also prefilter the roughness map based on the bump values.
  44464. */
  44465. _this._enableSpecularAntiAliasing = false;
  44466. /**
  44467. * Stores the available render targets.
  44468. */
  44469. _this._renderTargets = new BABYLON.SmartArray(16);
  44470. /**
  44471. * Sets the global ambient color for the material used in lighting calculations.
  44472. */
  44473. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44474. /**
  44475. * If set to true, no lighting calculations will be applied.
  44476. */
  44477. _this._unlit = false;
  44478. // Setup the default processing configuration to the scene.
  44479. _this._attachImageProcessingConfiguration(null);
  44480. _this.getRenderTargetTextures = function () {
  44481. _this._renderTargets.reset();
  44482. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44483. _this._renderTargets.push(_this._reflectionTexture);
  44484. }
  44485. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44486. _this._renderTargets.push(_this._refractionTexture);
  44487. }
  44488. return _this._renderTargets;
  44489. };
  44490. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44491. return _this;
  44492. }
  44493. /**
  44494. * Attaches a new image processing configuration to the PBR Material.
  44495. * @param configuration
  44496. */
  44497. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44498. var _this = this;
  44499. if (configuration === this._imageProcessingConfiguration) {
  44500. return;
  44501. }
  44502. // Detaches observer.
  44503. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44504. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44505. }
  44506. // Pick the scene configuration if needed.
  44507. if (!configuration) {
  44508. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44509. }
  44510. else {
  44511. this._imageProcessingConfiguration = configuration;
  44512. }
  44513. // Attaches observer.
  44514. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44515. _this._markAllSubMeshesAsImageProcessingDirty();
  44516. });
  44517. };
  44518. /**
  44519. * Gets the name of the material class.
  44520. */
  44521. PBRBaseMaterial.prototype.getClassName = function () {
  44522. return "PBRBaseMaterial";
  44523. };
  44524. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44525. /**
  44526. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44527. */
  44528. get: function () {
  44529. return this._useLogarithmicDepth;
  44530. },
  44531. /**
  44532. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44533. */
  44534. set: function (value) {
  44535. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44536. },
  44537. enumerable: true,
  44538. configurable: true
  44539. });
  44540. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44541. /**
  44542. * Gets the current transparency mode.
  44543. */
  44544. get: function () {
  44545. return this._transparencyMode;
  44546. },
  44547. /**
  44548. * Sets the transparency mode of the material.
  44549. */
  44550. set: function (value) {
  44551. if (this._transparencyMode === value) {
  44552. return;
  44553. }
  44554. this._transparencyMode = value;
  44555. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44556. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44557. },
  44558. enumerable: true,
  44559. configurable: true
  44560. });
  44561. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44562. /**
  44563. * Returns true if alpha blending should be disabled.
  44564. */
  44565. get: function () {
  44566. return (this._linkRefractionWithTransparency ||
  44567. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44568. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44569. },
  44570. enumerable: true,
  44571. configurable: true
  44572. });
  44573. /**
  44574. * Specifies whether or not this material should be rendered in alpha blend mode.
  44575. */
  44576. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44577. if (this._disableAlphaBlending) {
  44578. return false;
  44579. }
  44580. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44581. };
  44582. /**
  44583. * Specifies if the mesh will require alpha blending.
  44584. * @param mesh - BJS mesh.
  44585. */
  44586. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44587. if (this._disableAlphaBlending) {
  44588. return false;
  44589. }
  44590. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44591. };
  44592. /**
  44593. * Specifies whether or not this material should be rendered in alpha test mode.
  44594. */
  44595. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44596. if (this._forceAlphaTest) {
  44597. return true;
  44598. }
  44599. if (this._linkRefractionWithTransparency) {
  44600. return false;
  44601. }
  44602. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44603. };
  44604. /**
  44605. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44606. */
  44607. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44608. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44609. };
  44610. /**
  44611. * Gets the texture used for the alpha test.
  44612. */
  44613. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44614. return this._albedoTexture;
  44615. };
  44616. /**
  44617. * Specifies that the submesh is ready to be used.
  44618. * @param mesh - BJS mesh.
  44619. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44620. * @param useInstances - Specifies that instances should be used.
  44621. * @returns - boolean indicating that the submesh is ready or not.
  44622. */
  44623. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44624. if (subMesh.effect && this.isFrozen) {
  44625. if (this._wasPreviouslyReady) {
  44626. return true;
  44627. }
  44628. }
  44629. if (!subMesh._materialDefines) {
  44630. subMesh._materialDefines = new PBRMaterialDefines();
  44631. }
  44632. var defines = subMesh._materialDefines;
  44633. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44634. if (defines._renderId === this.getScene().getRenderId()) {
  44635. return true;
  44636. }
  44637. }
  44638. var scene = this.getScene();
  44639. var engine = scene.getEngine();
  44640. if (defines._areTexturesDirty) {
  44641. if (scene.texturesEnabled) {
  44642. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44643. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44644. return false;
  44645. }
  44646. }
  44647. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44648. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44649. return false;
  44650. }
  44651. }
  44652. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44653. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44654. return false;
  44655. }
  44656. }
  44657. var reflectionTexture = this._getReflectionTexture();
  44658. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44659. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44660. return false;
  44661. }
  44662. }
  44663. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44664. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44665. return false;
  44666. }
  44667. }
  44668. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44669. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44670. return false;
  44671. }
  44672. }
  44673. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44674. if (this._metallicTexture) {
  44675. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44676. return false;
  44677. }
  44678. }
  44679. else if (this._reflectivityTexture) {
  44680. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44681. return false;
  44682. }
  44683. }
  44684. if (this._microSurfaceTexture) {
  44685. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44686. return false;
  44687. }
  44688. }
  44689. }
  44690. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44691. // Bump texture cannot be not blocking.
  44692. if (!this._bumpTexture.isReady()) {
  44693. return false;
  44694. }
  44695. }
  44696. var refractionTexture = this._getRefractionTexture();
  44697. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44698. if (!refractionTexture.isReadyOrNotBlocking()) {
  44699. return false;
  44700. }
  44701. }
  44702. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44703. // This is blocking.
  44704. if (!this._environmentBRDFTexture.isReady()) {
  44705. return false;
  44706. }
  44707. }
  44708. }
  44709. }
  44710. if (defines._areImageProcessingDirty) {
  44711. if (!this._imageProcessingConfiguration.isReady()) {
  44712. return false;
  44713. }
  44714. }
  44715. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44716. mesh.createNormals(true);
  44717. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44718. }
  44719. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44720. if (effect) {
  44721. scene.resetCachedMaterial();
  44722. subMesh.setEffect(effect, defines);
  44723. this.buildUniformLayout();
  44724. }
  44725. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44726. return false;
  44727. }
  44728. defines._renderId = scene.getRenderId();
  44729. this._wasPreviouslyReady = true;
  44730. return true;
  44731. };
  44732. /**
  44733. * Specifies if the material uses metallic roughness workflow.
  44734. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44735. */
  44736. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44737. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44738. return true;
  44739. }
  44740. return false;
  44741. };
  44742. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44743. if (onCompiled === void 0) { onCompiled = null; }
  44744. if (onError === void 0) { onError = null; }
  44745. if (useInstances === void 0) { useInstances = null; }
  44746. if (useClipPlane === void 0) { useClipPlane = null; }
  44747. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44748. if (!defines.isDirty) {
  44749. return null;
  44750. }
  44751. defines.markAsProcessed();
  44752. var scene = this.getScene();
  44753. var engine = scene.getEngine();
  44754. // Fallbacks
  44755. var fallbacks = new BABYLON.EffectFallbacks();
  44756. var fallbackRank = 0;
  44757. if (defines.USESPHERICALINVERTEX) {
  44758. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44759. }
  44760. if (defines.FOG) {
  44761. fallbacks.addFallback(fallbackRank, "FOG");
  44762. }
  44763. if (defines.POINTSIZE) {
  44764. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44765. }
  44766. if (defines.LOGARITHMICDEPTH) {
  44767. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44768. }
  44769. if (defines.PARALLAX) {
  44770. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44771. }
  44772. if (defines.PARALLAXOCCLUSION) {
  44773. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44774. }
  44775. if (defines.ENVIRONMENTBRDF) {
  44776. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44777. }
  44778. if (defines.TANGENT) {
  44779. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44780. }
  44781. if (defines.BUMP) {
  44782. fallbacks.addFallback(fallbackRank++, "BUMP");
  44783. }
  44784. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44785. if (defines.SPECULARTERM) {
  44786. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44787. }
  44788. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44789. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44790. }
  44791. if (defines.LIGHTMAP) {
  44792. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44793. }
  44794. if (defines.NORMAL) {
  44795. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44796. }
  44797. if (defines.AMBIENT) {
  44798. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44799. }
  44800. if (defines.EMISSIVE) {
  44801. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44802. }
  44803. if (defines.VERTEXCOLOR) {
  44804. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44805. }
  44806. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44807. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44808. }
  44809. if (defines.MORPHTARGETS) {
  44810. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44811. }
  44812. //Attributes
  44813. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44814. if (defines.NORMAL) {
  44815. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44816. }
  44817. if (defines.TANGENT) {
  44818. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44819. }
  44820. if (defines.UV1) {
  44821. attribs.push(BABYLON.VertexBuffer.UVKind);
  44822. }
  44823. if (defines.UV2) {
  44824. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44825. }
  44826. if (defines.VERTEXCOLOR) {
  44827. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44828. }
  44829. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44830. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44831. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44832. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44833. "vFogInfos", "vFogColor", "pointSize",
  44834. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44835. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44836. "mBones",
  44837. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44838. "vLightingIntensity",
  44839. "logarithmicDepthConstant",
  44840. "vSphericalX", "vSphericalY", "vSphericalZ",
  44841. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44842. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44843. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44844. "vTangentSpaceParams"
  44845. ];
  44846. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44847. "bumpSampler", "lightmapSampler", "opacitySampler",
  44848. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44849. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44850. "microSurfaceSampler", "environmentBrdfSampler"];
  44851. var uniformBuffers = ["Material", "Scene"];
  44852. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44853. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44854. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44855. uniformsNames: uniforms,
  44856. uniformBuffersNames: uniformBuffers,
  44857. samplers: samplers,
  44858. defines: defines,
  44859. maxSimultaneousLights: this._maxSimultaneousLights
  44860. });
  44861. var join = defines.toString();
  44862. return engine.createEffect("pbr", {
  44863. attributes: attribs,
  44864. uniformsNames: uniforms,
  44865. uniformBuffersNames: uniformBuffers,
  44866. samplers: samplers,
  44867. defines: join,
  44868. fallbacks: fallbacks,
  44869. onCompiled: onCompiled,
  44870. onError: onError,
  44871. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44872. }, engine);
  44873. };
  44874. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44875. if (useInstances === void 0) { useInstances = null; }
  44876. if (useClipPlane === void 0) { useClipPlane = null; }
  44877. var scene = this.getScene();
  44878. var engine = scene.getEngine();
  44879. // Lights
  44880. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44881. defines._needNormals = true;
  44882. // Textures
  44883. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44884. if (defines._areTexturesDirty) {
  44885. defines._needUVs = false;
  44886. if (scene.texturesEnabled) {
  44887. if (scene.getEngine().getCaps().textureLOD) {
  44888. defines.LODBASEDMICROSFURACE = true;
  44889. }
  44890. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44891. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44892. }
  44893. else {
  44894. defines.ALBEDO = false;
  44895. }
  44896. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44897. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44898. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44899. }
  44900. else {
  44901. defines.AMBIENT = false;
  44902. }
  44903. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44904. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44905. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44906. }
  44907. else {
  44908. defines.OPACITY = false;
  44909. }
  44910. var reflectionTexture = this._getReflectionTexture();
  44911. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44912. defines.REFLECTION = true;
  44913. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44914. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44915. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44916. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44917. defines.INVERTCUBICMAP = true;
  44918. }
  44919. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44920. switch (reflectionTexture.coordinatesMode) {
  44921. case BABYLON.Texture.EXPLICIT_MODE:
  44922. defines.REFLECTIONMAP_EXPLICIT = true;
  44923. break;
  44924. case BABYLON.Texture.PLANAR_MODE:
  44925. defines.REFLECTIONMAP_PLANAR = true;
  44926. break;
  44927. case BABYLON.Texture.PROJECTION_MODE:
  44928. defines.REFLECTIONMAP_PROJECTION = true;
  44929. break;
  44930. case BABYLON.Texture.SKYBOX_MODE:
  44931. defines.REFLECTIONMAP_SKYBOX = true;
  44932. break;
  44933. case BABYLON.Texture.SPHERICAL_MODE:
  44934. defines.REFLECTIONMAP_SPHERICAL = true;
  44935. break;
  44936. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44937. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44938. break;
  44939. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44940. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44941. break;
  44942. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44943. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44944. break;
  44945. case BABYLON.Texture.CUBIC_MODE:
  44946. case BABYLON.Texture.INVCUBIC_MODE:
  44947. default:
  44948. defines.REFLECTIONMAP_CUBIC = true;
  44949. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44950. break;
  44951. }
  44952. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44953. if (reflectionTexture.sphericalPolynomial) {
  44954. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44955. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44956. defines.USESPHERICALINVERTEX = false;
  44957. }
  44958. else {
  44959. defines.USESPHERICALINVERTEX = true;
  44960. }
  44961. }
  44962. }
  44963. }
  44964. else {
  44965. defines.REFLECTION = false;
  44966. defines.REFLECTIONMAP_3D = false;
  44967. defines.REFLECTIONMAP_SPHERICAL = false;
  44968. defines.REFLECTIONMAP_PLANAR = false;
  44969. defines.REFLECTIONMAP_CUBIC = false;
  44970. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44971. defines.REFLECTIONMAP_PROJECTION = false;
  44972. defines.REFLECTIONMAP_SKYBOX = false;
  44973. defines.REFLECTIONMAP_EXPLICIT = false;
  44974. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44975. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44976. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44977. defines.INVERTCUBICMAP = false;
  44978. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44979. defines.USESPHERICALINVERTEX = false;
  44980. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44981. defines.LODINREFLECTIONALPHA = false;
  44982. defines.GAMMAREFLECTION = false;
  44983. }
  44984. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44985. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44986. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44987. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44988. }
  44989. else {
  44990. defines.LIGHTMAP = false;
  44991. }
  44992. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44993. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44994. }
  44995. else {
  44996. defines.EMISSIVE = false;
  44997. }
  44998. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44999. if (this._metallicTexture) {
  45000. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45001. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45002. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45003. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45004. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45005. }
  45006. else if (this._reflectivityTexture) {
  45007. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45008. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45009. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45010. }
  45011. else {
  45012. defines.REFLECTIVITY = false;
  45013. }
  45014. if (this._microSurfaceTexture) {
  45015. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45016. }
  45017. else {
  45018. defines.MICROSURFACEMAP = false;
  45019. }
  45020. }
  45021. else {
  45022. defines.REFLECTIVITY = false;
  45023. defines.MICROSURFACEMAP = false;
  45024. }
  45025. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45026. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45027. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45028. defines.PARALLAX = true;
  45029. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45030. }
  45031. else {
  45032. defines.PARALLAX = false;
  45033. }
  45034. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45035. }
  45036. else {
  45037. defines.BUMP = false;
  45038. }
  45039. var refractionTexture = this._getRefractionTexture();
  45040. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45041. defines.REFRACTION = true;
  45042. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45043. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45044. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45045. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45046. if (this._linkRefractionWithTransparency) {
  45047. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45048. }
  45049. }
  45050. else {
  45051. defines.REFRACTION = false;
  45052. }
  45053. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45054. defines.ENVIRONMENTBRDF = true;
  45055. }
  45056. else {
  45057. defines.ENVIRONMENTBRDF = false;
  45058. }
  45059. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45060. defines.ALPHAFROMALBEDO = true;
  45061. }
  45062. else {
  45063. defines.ALPHAFROMALBEDO = false;
  45064. }
  45065. }
  45066. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45067. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45068. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45069. if (!this.backFaceCulling && this._twoSidedLighting) {
  45070. defines.TWOSIDEDLIGHTING = true;
  45071. }
  45072. else {
  45073. defines.TWOSIDEDLIGHTING = false;
  45074. }
  45075. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45076. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45077. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45078. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45079. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45080. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45081. }
  45082. if (defines._areImageProcessingDirty) {
  45083. this._imageProcessingConfiguration.prepareDefines(defines);
  45084. }
  45085. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45086. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45087. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45088. // Misc.
  45089. if (defines._areMiscDirty) {
  45090. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45091. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45092. }
  45093. // Values that need to be evaluated on every frame
  45094. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45095. // Attribs
  45096. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45097. };
  45098. /**
  45099. * Force shader compilation
  45100. */
  45101. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45102. var _this = this;
  45103. var localOptions = __assign({ clipPlane: false }, options);
  45104. var defines = new PBRMaterialDefines();
  45105. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45106. if (effect.isReady()) {
  45107. if (onCompiled) {
  45108. onCompiled(this);
  45109. }
  45110. }
  45111. else {
  45112. effect.onCompileObservable.add(function () {
  45113. if (onCompiled) {
  45114. onCompiled(_this);
  45115. }
  45116. });
  45117. }
  45118. };
  45119. /**
  45120. * Initializes the uniform buffer layout for the shader.
  45121. */
  45122. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45123. // Order is important !
  45124. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45125. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45126. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45127. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45128. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45129. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45130. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45131. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45132. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45133. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45134. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45135. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45136. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45137. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45138. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45139. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45140. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45141. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45142. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45143. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45144. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45145. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45146. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45147. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45148. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45149. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45150. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45151. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45152. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45153. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45154. this._uniformBuffer.addUniform("pointSize", 1);
  45155. this._uniformBuffer.create();
  45156. };
  45157. /**
  45158. * Unbinds the textures.
  45159. */
  45160. PBRBaseMaterial.prototype.unbind = function () {
  45161. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45162. this._uniformBuffer.setTexture("reflectionSampler", null);
  45163. }
  45164. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45165. this._uniformBuffer.setTexture("refractionSampler", null);
  45166. }
  45167. _super.prototype.unbind.call(this);
  45168. };
  45169. /**
  45170. * Binds the submesh data.
  45171. * @param world - The world matrix.
  45172. * @param mesh - The BJS mesh.
  45173. * @param subMesh - A submesh of the BJS mesh.
  45174. */
  45175. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45176. var scene = this.getScene();
  45177. var defines = subMesh._materialDefines;
  45178. if (!defines) {
  45179. return;
  45180. }
  45181. var effect = subMesh.effect;
  45182. if (!effect) {
  45183. return;
  45184. }
  45185. this._activeEffect = effect;
  45186. // Matrices
  45187. this.bindOnlyWorldMatrix(world);
  45188. // Normal Matrix
  45189. if (defines.OBJECTSPACE_NORMALMAP) {
  45190. world.toNormalMatrix(this._normalMatrix);
  45191. this.bindOnlyNormalMatrix(this._normalMatrix);
  45192. }
  45193. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45194. // Bones
  45195. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45196. var reflectionTexture = null;
  45197. if (mustRebind) {
  45198. this._uniformBuffer.bindToEffect(effect, "Material");
  45199. this.bindViewProjection(effect);
  45200. reflectionTexture = this._getReflectionTexture();
  45201. var refractionTexture = this._getRefractionTexture();
  45202. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45203. // Texture uniforms
  45204. if (scene.texturesEnabled) {
  45205. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45206. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45207. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45208. }
  45209. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45210. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45211. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45212. }
  45213. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45214. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45215. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45216. }
  45217. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45218. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45219. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45220. if (reflectionTexture.boundingBoxSize) {
  45221. var cubeTexture = reflectionTexture;
  45222. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45223. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45224. }
  45225. var polynomials = reflectionTexture.sphericalPolynomial;
  45226. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45227. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45228. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45229. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45230. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45231. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45232. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45233. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45234. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45235. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45236. }
  45237. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45238. }
  45239. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45240. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45241. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45242. }
  45243. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45244. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45245. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45246. }
  45247. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45248. if (this._metallicTexture) {
  45249. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45250. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45251. }
  45252. else if (this._reflectivityTexture) {
  45253. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45254. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45255. }
  45256. if (this._microSurfaceTexture) {
  45257. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45258. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45259. }
  45260. }
  45261. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45262. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45263. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45264. if (scene._mirroredCameraPosition) {
  45265. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45266. }
  45267. else {
  45268. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45269. }
  45270. }
  45271. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45272. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45273. var depth = 1.0;
  45274. if (!refractionTexture.isCube) {
  45275. if (refractionTexture.depth) {
  45276. depth = refractionTexture.depth;
  45277. }
  45278. }
  45279. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45280. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45281. }
  45282. }
  45283. // Point size
  45284. if (this.pointsCloud) {
  45285. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45286. }
  45287. // Colors
  45288. if (defines.METALLICWORKFLOW) {
  45289. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45290. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45291. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45292. }
  45293. else {
  45294. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45295. }
  45296. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45297. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45298. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45299. // Misc
  45300. this._lightingInfos.x = this._directIntensity;
  45301. this._lightingInfos.y = this._emissiveIntensity;
  45302. this._lightingInfos.z = this._environmentIntensity;
  45303. this._lightingInfos.w = this._specularIntensity;
  45304. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45305. }
  45306. // Textures
  45307. if (scene.texturesEnabled) {
  45308. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45309. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45310. }
  45311. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45312. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45313. }
  45314. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45315. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45316. }
  45317. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45318. if (defines.LODBASEDMICROSFURACE) {
  45319. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45320. }
  45321. else {
  45322. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45323. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45324. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45325. }
  45326. }
  45327. if (defines.ENVIRONMENTBRDF) {
  45328. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45329. }
  45330. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45331. if (defines.LODBASEDMICROSFURACE) {
  45332. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45333. }
  45334. else {
  45335. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45336. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45337. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45338. }
  45339. }
  45340. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45341. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45342. }
  45343. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45344. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45345. }
  45346. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45347. if (this._metallicTexture) {
  45348. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45349. }
  45350. else if (this._reflectivityTexture) {
  45351. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45352. }
  45353. if (this._microSurfaceTexture) {
  45354. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45355. }
  45356. }
  45357. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45358. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45359. }
  45360. }
  45361. // Clip plane
  45362. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45363. // Colors
  45364. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45365. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45366. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45367. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45368. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45369. }
  45370. if (mustRebind || !this.isFrozen) {
  45371. // Lights
  45372. if (scene.lightsEnabled && !this._disableLighting) {
  45373. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45374. }
  45375. // View
  45376. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45377. this.bindView(effect);
  45378. }
  45379. // Fog
  45380. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45381. // Morph targets
  45382. if (defines.NUM_MORPH_INFLUENCERS) {
  45383. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45384. }
  45385. // image processing
  45386. this._imageProcessingConfiguration.bind(this._activeEffect);
  45387. // Log. depth
  45388. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45389. }
  45390. this._uniformBuffer.update();
  45391. this._afterBind(mesh);
  45392. };
  45393. /**
  45394. * Returns the animatable textures.
  45395. * @returns - Array of animatable textures.
  45396. */
  45397. PBRBaseMaterial.prototype.getAnimatables = function () {
  45398. var results = [];
  45399. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45400. results.push(this._albedoTexture);
  45401. }
  45402. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45403. results.push(this._ambientTexture);
  45404. }
  45405. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45406. results.push(this._opacityTexture);
  45407. }
  45408. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45409. results.push(this._reflectionTexture);
  45410. }
  45411. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45412. results.push(this._emissiveTexture);
  45413. }
  45414. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45415. results.push(this._metallicTexture);
  45416. }
  45417. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45418. results.push(this._reflectivityTexture);
  45419. }
  45420. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45421. results.push(this._bumpTexture);
  45422. }
  45423. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45424. results.push(this._lightmapTexture);
  45425. }
  45426. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45427. results.push(this._refractionTexture);
  45428. }
  45429. return results;
  45430. };
  45431. /**
  45432. * Returns the texture used for reflections.
  45433. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45434. */
  45435. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45436. if (this._reflectionTexture) {
  45437. return this._reflectionTexture;
  45438. }
  45439. return this.getScene().environmentTexture;
  45440. };
  45441. /**
  45442. * Returns the texture used for refraction or null if none is used.
  45443. * @returns - Refection texture if present. If no refraction texture and refraction
  45444. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45445. */
  45446. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45447. if (this._refractionTexture) {
  45448. return this._refractionTexture;
  45449. }
  45450. if (this._linkRefractionWithTransparency) {
  45451. return this.getScene().environmentTexture;
  45452. }
  45453. return null;
  45454. };
  45455. /**
  45456. * Disposes the resources of the material.
  45457. * @param forceDisposeEffect - Forces the disposal of effects.
  45458. * @param forceDisposeTextures - Forces the disposal of all textures.
  45459. */
  45460. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45461. if (forceDisposeTextures) {
  45462. if (this._albedoTexture) {
  45463. this._albedoTexture.dispose();
  45464. }
  45465. if (this._ambientTexture) {
  45466. this._ambientTexture.dispose();
  45467. }
  45468. if (this._opacityTexture) {
  45469. this._opacityTexture.dispose();
  45470. }
  45471. if (this._reflectionTexture) {
  45472. this._reflectionTexture.dispose();
  45473. }
  45474. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45475. this._environmentBRDFTexture.dispose();
  45476. }
  45477. if (this._emissiveTexture) {
  45478. this._emissiveTexture.dispose();
  45479. }
  45480. if (this._metallicTexture) {
  45481. this._metallicTexture.dispose();
  45482. }
  45483. if (this._reflectivityTexture) {
  45484. this._reflectivityTexture.dispose();
  45485. }
  45486. if (this._bumpTexture) {
  45487. this._bumpTexture.dispose();
  45488. }
  45489. if (this._lightmapTexture) {
  45490. this._lightmapTexture.dispose();
  45491. }
  45492. if (this._refractionTexture) {
  45493. this._refractionTexture.dispose();
  45494. }
  45495. }
  45496. this._renderTargets.dispose();
  45497. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45498. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45499. }
  45500. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45501. };
  45502. /**
  45503. * Stores the reflectivity values based on metallic roughness workflow.
  45504. */
  45505. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45506. __decorate([
  45507. BABYLON.serializeAsImageProcessingConfiguration()
  45508. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45509. __decorate([
  45510. BABYLON.serialize()
  45511. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45512. __decorate([
  45513. BABYLON.serialize()
  45514. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45515. return PBRBaseMaterial;
  45516. }(BABYLON.PushMaterial));
  45517. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45518. })(BABYLON || (BABYLON = {}));
  45519. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45520. var BABYLON;
  45521. (function (BABYLON) {
  45522. /**
  45523. * The Physically based simple base material of BJS.
  45524. *
  45525. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45526. * It is used as the base class for both the specGloss and metalRough conventions.
  45527. */
  45528. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45529. __extends(PBRBaseSimpleMaterial, _super);
  45530. /**
  45531. * Instantiates a new PBRMaterial instance.
  45532. *
  45533. * @param name The material name
  45534. * @param scene The scene the material will be use in.
  45535. */
  45536. function PBRBaseSimpleMaterial(name, scene) {
  45537. var _this = _super.call(this, name, scene) || this;
  45538. /**
  45539. * Number of Simultaneous lights allowed on the material.
  45540. */
  45541. _this.maxSimultaneousLights = 4;
  45542. /**
  45543. * If sets to true, disables all the lights affecting the material.
  45544. */
  45545. _this.disableLighting = false;
  45546. /**
  45547. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45548. */
  45549. _this.invertNormalMapX = false;
  45550. /**
  45551. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45552. */
  45553. _this.invertNormalMapY = false;
  45554. /**
  45555. * Emissivie color used to self-illuminate the model.
  45556. */
  45557. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45558. /**
  45559. * Occlusion Channel Strenght.
  45560. */
  45561. _this.occlusionStrength = 1.0;
  45562. _this.useLightmapAsShadowmap = false;
  45563. _this._useAlphaFromAlbedoTexture = true;
  45564. _this._useAmbientInGrayScale = true;
  45565. return _this;
  45566. }
  45567. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45568. /**
  45569. * Gets the current double sided mode.
  45570. */
  45571. get: function () {
  45572. return this._twoSidedLighting;
  45573. },
  45574. /**
  45575. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45576. */
  45577. set: function (value) {
  45578. if (this._twoSidedLighting === value) {
  45579. return;
  45580. }
  45581. this._twoSidedLighting = value;
  45582. this.backFaceCulling = !value;
  45583. this._markAllSubMeshesAsTexturesDirty();
  45584. },
  45585. enumerable: true,
  45586. configurable: true
  45587. });
  45588. /**
  45589. * Return the active textures of the material.
  45590. */
  45591. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45592. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45593. if (this.environmentTexture) {
  45594. activeTextures.push(this.environmentTexture);
  45595. }
  45596. if (this.normalTexture) {
  45597. activeTextures.push(this.normalTexture);
  45598. }
  45599. if (this.emissiveTexture) {
  45600. activeTextures.push(this.emissiveTexture);
  45601. }
  45602. if (this.occlusionTexture) {
  45603. activeTextures.push(this.occlusionTexture);
  45604. }
  45605. if (this.lightmapTexture) {
  45606. activeTextures.push(this.lightmapTexture);
  45607. }
  45608. return activeTextures;
  45609. };
  45610. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45611. if (_super.prototype.hasTexture.call(this, texture)) {
  45612. return true;
  45613. }
  45614. if (this.lightmapTexture === texture) {
  45615. return true;
  45616. }
  45617. return false;
  45618. };
  45619. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45620. return "PBRBaseSimpleMaterial";
  45621. };
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45625. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45629. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45630. __decorate([
  45631. BABYLON.serializeAsTexture(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45633. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45637. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45641. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45642. __decorate([
  45643. BABYLON.serializeAsTexture(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45645. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45646. __decorate([
  45647. BABYLON.serializeAsColor3("emissive"),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45650. __decorate([
  45651. BABYLON.serializeAsTexture(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45657. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45658. __decorate([
  45659. BABYLON.serializeAsTexture(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45661. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45665. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45666. __decorate([
  45667. BABYLON.serialize()
  45668. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45669. __decorate([
  45670. BABYLON.serializeAsTexture(),
  45671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45672. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45673. __decorate([
  45674. BABYLON.serialize(),
  45675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45676. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45677. return PBRBaseSimpleMaterial;
  45678. }(BABYLON.PBRBaseMaterial));
  45679. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45680. })(BABYLON || (BABYLON = {}));
  45681. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45682. var BABYLON;
  45683. (function (BABYLON) {
  45684. /**
  45685. * The Physically based material of BJS.
  45686. *
  45687. * This offers the main features of a standard PBR material.
  45688. * For more information, please refer to the documentation :
  45689. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45690. */
  45691. var PBRMaterial = /** @class */ (function (_super) {
  45692. __extends(PBRMaterial, _super);
  45693. /**
  45694. * Instantiates a new PBRMaterial instance.
  45695. *
  45696. * @param name The material name
  45697. * @param scene The scene the material will be use in.
  45698. */
  45699. function PBRMaterial(name, scene) {
  45700. var _this = _super.call(this, name, scene) || this;
  45701. /**
  45702. * Intensity of the direct lights e.g. the four lights available in your scene.
  45703. * This impacts both the direct diffuse and specular highlights.
  45704. */
  45705. _this.directIntensity = 1.0;
  45706. /**
  45707. * Intensity of the emissive part of the material.
  45708. * This helps controlling the emissive effect without modifying the emissive color.
  45709. */
  45710. _this.emissiveIntensity = 1.0;
  45711. /**
  45712. * Intensity of the environment e.g. how much the environment will light the object
  45713. * either through harmonics for rough material or through the refelction for shiny ones.
  45714. */
  45715. _this.environmentIntensity = 1.0;
  45716. /**
  45717. * This is a special control allowing the reduction of the specular highlights coming from the
  45718. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45719. */
  45720. _this.specularIntensity = 1.0;
  45721. /**
  45722. * Debug Control allowing disabling the bump map on this material.
  45723. */
  45724. _this.disableBumpMap = false;
  45725. /**
  45726. * AKA Occlusion Texture Intensity in other nomenclature.
  45727. */
  45728. _this.ambientTextureStrength = 1.0;
  45729. /**
  45730. * The color of a material in ambient lighting.
  45731. */
  45732. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45733. /**
  45734. * AKA Diffuse Color in other nomenclature.
  45735. */
  45736. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45737. /**
  45738. * AKA Specular Color in other nomenclature.
  45739. */
  45740. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45741. /**
  45742. * The color reflected from the material.
  45743. */
  45744. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45745. /**
  45746. * The color emitted from the material.
  45747. */
  45748. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45749. /**
  45750. * AKA Glossiness in other nomenclature.
  45751. */
  45752. _this.microSurface = 1.0;
  45753. /**
  45754. * source material index of refraction (IOR)' / 'destination material IOR.
  45755. */
  45756. _this.indexOfRefraction = 0.66;
  45757. /**
  45758. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45759. */
  45760. _this.invertRefractionY = false;
  45761. /**
  45762. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45763. * Materials half opaque for instance using refraction could benefit from this control.
  45764. */
  45765. _this.linkRefractionWithTransparency = false;
  45766. _this.useLightmapAsShadowmap = false;
  45767. /**
  45768. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45769. */
  45770. _this.useAlphaFromAlbedoTexture = false;
  45771. /**
  45772. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45773. */
  45774. _this.forceAlphaTest = false;
  45775. /**
  45776. * Defines the alpha limits in alpha test mode.
  45777. */
  45778. _this.alphaCutOff = 0.4;
  45779. /**
  45780. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45781. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45782. */
  45783. _this.useSpecularOverAlpha = true;
  45784. /**
  45785. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45786. */
  45787. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45788. /**
  45789. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45790. */
  45791. _this.useRoughnessFromMetallicTextureAlpha = true;
  45792. /**
  45793. * Specifies if the metallic texture contains the roughness information in its green channel.
  45794. */
  45795. _this.useRoughnessFromMetallicTextureGreen = false;
  45796. /**
  45797. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45798. */
  45799. _this.useMetallnessFromMetallicTextureBlue = false;
  45800. /**
  45801. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45802. */
  45803. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45804. /**
  45805. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45806. */
  45807. _this.useAmbientInGrayScale = false;
  45808. /**
  45809. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45810. * The material will try to infer what glossiness each pixel should be.
  45811. */
  45812. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45813. /**
  45814. * BJS is using an harcoded light falloff based on a manually sets up range.
  45815. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45816. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45817. */
  45818. _this.usePhysicalLightFalloff = true;
  45819. /**
  45820. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45821. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45822. */
  45823. _this.useRadianceOverAlpha = true;
  45824. /**
  45825. * Allows using an object space normal map (instead of tangent space).
  45826. */
  45827. _this.useObjectSpaceNormalMap = false;
  45828. /**
  45829. * Allows using the bump map in parallax mode.
  45830. */
  45831. _this.useParallax = false;
  45832. /**
  45833. * Allows using the bump map in parallax occlusion mode.
  45834. */
  45835. _this.useParallaxOcclusion = false;
  45836. /**
  45837. * Controls the scale bias of the parallax mode.
  45838. */
  45839. _this.parallaxScaleBias = 0.05;
  45840. /**
  45841. * If sets to true, disables all the lights affecting the material.
  45842. */
  45843. _this.disableLighting = false;
  45844. /**
  45845. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45846. */
  45847. _this.forceIrradianceInFragment = false;
  45848. /**
  45849. * Number of Simultaneous lights allowed on the material.
  45850. */
  45851. _this.maxSimultaneousLights = 4;
  45852. /**
  45853. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45854. */
  45855. _this.invertNormalMapX = false;
  45856. /**
  45857. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45858. */
  45859. _this.invertNormalMapY = false;
  45860. /**
  45861. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45862. */
  45863. _this.twoSidedLighting = false;
  45864. /**
  45865. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45866. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45867. */
  45868. _this.useAlphaFresnel = false;
  45869. /**
  45870. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45871. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45872. */
  45873. _this.useLinearAlphaFresnel = false;
  45874. /**
  45875. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45876. * And/Or occlude the blended part.
  45877. */
  45878. _this.environmentBRDFTexture = null;
  45879. /**
  45880. * Force normal to face away from face.
  45881. */
  45882. _this.forceNormalForward = false;
  45883. /**
  45884. * Enables specular anti aliasing in the PBR shader.
  45885. * It will both interacts on the Geometry for analytical and IBL lighting.
  45886. * It also prefilter the roughness map based on the bump values.
  45887. */
  45888. _this.enableSpecularAntiAliasing = false;
  45889. /**
  45890. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45891. * makes the reflect vector face the model (under horizon).
  45892. */
  45893. _this.useHorizonOcclusion = true;
  45894. /**
  45895. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45896. * too much the area relying on ambient texture to define their ambient occlusion.
  45897. */
  45898. _this.useRadianceOcclusion = true;
  45899. /**
  45900. * If set to true, no lighting calculations will be applied.
  45901. */
  45902. _this.unlit = false;
  45903. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45904. return _this;
  45905. }
  45906. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45907. /**
  45908. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45909. */
  45910. get: function () {
  45911. return this._PBRMATERIAL_OPAQUE;
  45912. },
  45913. enumerable: true,
  45914. configurable: true
  45915. });
  45916. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45917. /**
  45918. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45919. */
  45920. get: function () {
  45921. return this._PBRMATERIAL_ALPHATEST;
  45922. },
  45923. enumerable: true,
  45924. configurable: true
  45925. });
  45926. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45927. /**
  45928. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45929. */
  45930. get: function () {
  45931. return this._PBRMATERIAL_ALPHABLEND;
  45932. },
  45933. enumerable: true,
  45934. configurable: true
  45935. });
  45936. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45937. /**
  45938. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45939. * They are also discarded below the alpha cutoff threshold to improve performances.
  45940. */
  45941. get: function () {
  45942. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45943. },
  45944. enumerable: true,
  45945. configurable: true
  45946. });
  45947. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45948. /**
  45949. * Gets the image processing configuration used either in this material.
  45950. */
  45951. get: function () {
  45952. return this._imageProcessingConfiguration;
  45953. },
  45954. /**
  45955. * Sets the Default image processing configuration used either in the this material.
  45956. *
  45957. * If sets to null, the scene one is in use.
  45958. */
  45959. set: function (value) {
  45960. this._attachImageProcessingConfiguration(value);
  45961. // Ensure the effect will be rebuilt.
  45962. this._markAllSubMeshesAsTexturesDirty();
  45963. },
  45964. enumerable: true,
  45965. configurable: true
  45966. });
  45967. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45968. /**
  45969. * Gets wether the color curves effect is enabled.
  45970. */
  45971. get: function () {
  45972. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45973. },
  45974. /**
  45975. * Sets wether the color curves effect is enabled.
  45976. */
  45977. set: function (value) {
  45978. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45979. },
  45980. enumerable: true,
  45981. configurable: true
  45982. });
  45983. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45984. /**
  45985. * Gets wether the color grading effect is enabled.
  45986. */
  45987. get: function () {
  45988. return this.imageProcessingConfiguration.colorGradingEnabled;
  45989. },
  45990. /**
  45991. * Gets wether the color grading effect is enabled.
  45992. */
  45993. set: function (value) {
  45994. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45995. },
  45996. enumerable: true,
  45997. configurable: true
  45998. });
  45999. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46000. /**
  46001. * Gets wether tonemapping is enabled or not.
  46002. */
  46003. get: function () {
  46004. return this._imageProcessingConfiguration.toneMappingEnabled;
  46005. },
  46006. /**
  46007. * Sets wether tonemapping is enabled or not
  46008. */
  46009. set: function (value) {
  46010. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46011. },
  46012. enumerable: true,
  46013. configurable: true
  46014. });
  46015. ;
  46016. ;
  46017. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46018. /**
  46019. * The camera exposure used on this material.
  46020. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46021. * This corresponds to a photographic exposure.
  46022. */
  46023. get: function () {
  46024. return this._imageProcessingConfiguration.exposure;
  46025. },
  46026. /**
  46027. * The camera exposure used on this material.
  46028. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46029. * This corresponds to a photographic exposure.
  46030. */
  46031. set: function (value) {
  46032. this._imageProcessingConfiguration.exposure = value;
  46033. },
  46034. enumerable: true,
  46035. configurable: true
  46036. });
  46037. ;
  46038. ;
  46039. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46040. /**
  46041. * Gets The camera contrast used on this material.
  46042. */
  46043. get: function () {
  46044. return this._imageProcessingConfiguration.contrast;
  46045. },
  46046. /**
  46047. * Sets The camera contrast used on this material.
  46048. */
  46049. set: function (value) {
  46050. this._imageProcessingConfiguration.contrast = value;
  46051. },
  46052. enumerable: true,
  46053. configurable: true
  46054. });
  46055. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46056. /**
  46057. * Gets the Color Grading 2D Lookup Texture.
  46058. */
  46059. get: function () {
  46060. return this._imageProcessingConfiguration.colorGradingTexture;
  46061. },
  46062. /**
  46063. * Sets the Color Grading 2D Lookup Texture.
  46064. */
  46065. set: function (value) {
  46066. this._imageProcessingConfiguration.colorGradingTexture = value;
  46067. },
  46068. enumerable: true,
  46069. configurable: true
  46070. });
  46071. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46072. /**
  46073. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46074. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46075. * 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;
  46076. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46077. */
  46078. get: function () {
  46079. return this._imageProcessingConfiguration.colorCurves;
  46080. },
  46081. /**
  46082. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46083. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46084. * 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;
  46085. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46086. */
  46087. set: function (value) {
  46088. this._imageProcessingConfiguration.colorCurves = value;
  46089. },
  46090. enumerable: true,
  46091. configurable: true
  46092. });
  46093. /**
  46094. * Returns the name of this material class.
  46095. */
  46096. PBRMaterial.prototype.getClassName = function () {
  46097. return "PBRMaterial";
  46098. };
  46099. /**
  46100. * Returns an array of the actively used textures.
  46101. * @returns - Array of BaseTextures
  46102. */
  46103. PBRMaterial.prototype.getActiveTextures = function () {
  46104. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46105. if (this._albedoTexture) {
  46106. activeTextures.push(this._albedoTexture);
  46107. }
  46108. if (this._ambientTexture) {
  46109. activeTextures.push(this._ambientTexture);
  46110. }
  46111. if (this._opacityTexture) {
  46112. activeTextures.push(this._opacityTexture);
  46113. }
  46114. if (this._reflectionTexture) {
  46115. activeTextures.push(this._reflectionTexture);
  46116. }
  46117. if (this._emissiveTexture) {
  46118. activeTextures.push(this._emissiveTexture);
  46119. }
  46120. if (this._reflectivityTexture) {
  46121. activeTextures.push(this._reflectivityTexture);
  46122. }
  46123. if (this._metallicTexture) {
  46124. activeTextures.push(this._metallicTexture);
  46125. }
  46126. if (this._microSurfaceTexture) {
  46127. activeTextures.push(this._microSurfaceTexture);
  46128. }
  46129. if (this._bumpTexture) {
  46130. activeTextures.push(this._bumpTexture);
  46131. }
  46132. if (this._lightmapTexture) {
  46133. activeTextures.push(this._lightmapTexture);
  46134. }
  46135. if (this._refractionTexture) {
  46136. activeTextures.push(this._refractionTexture);
  46137. }
  46138. return activeTextures;
  46139. };
  46140. /**
  46141. * Checks to see if a texture is used in the material.
  46142. * @param texture - Base texture to use.
  46143. * @returns - Boolean specifying if a texture is used in the material.
  46144. */
  46145. PBRMaterial.prototype.hasTexture = function (texture) {
  46146. if (_super.prototype.hasTexture.call(this, texture)) {
  46147. return true;
  46148. }
  46149. if (this._albedoTexture === texture) {
  46150. return true;
  46151. }
  46152. if (this._ambientTexture === texture) {
  46153. return true;
  46154. }
  46155. if (this._opacityTexture === texture) {
  46156. return true;
  46157. }
  46158. if (this._reflectionTexture === texture) {
  46159. return true;
  46160. }
  46161. if (this._reflectivityTexture === texture) {
  46162. return true;
  46163. }
  46164. if (this._metallicTexture === texture) {
  46165. return true;
  46166. }
  46167. if (this._microSurfaceTexture === texture) {
  46168. return true;
  46169. }
  46170. if (this._bumpTexture === texture) {
  46171. return true;
  46172. }
  46173. if (this._lightmapTexture === texture) {
  46174. return true;
  46175. }
  46176. if (this._refractionTexture === texture) {
  46177. return true;
  46178. }
  46179. return false;
  46180. };
  46181. /**
  46182. * Makes a duplicate of the current material.
  46183. * @param name - name to use for the new material.
  46184. */
  46185. PBRMaterial.prototype.clone = function (name) {
  46186. var _this = this;
  46187. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46188. clone.id = name;
  46189. clone.name = name;
  46190. return clone;
  46191. };
  46192. /**
  46193. * Serializes this PBR Material.
  46194. * @returns - An object with the serialized material.
  46195. */
  46196. PBRMaterial.prototype.serialize = function () {
  46197. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46198. serializationObject.customType = "BABYLON.PBRMaterial";
  46199. return serializationObject;
  46200. };
  46201. // Statics
  46202. /**
  46203. * Parses a PBR Material from a serialized object.
  46204. * @param source - Serialized object.
  46205. * @param scene - BJS scene instance.
  46206. * @param rootUrl - url for the scene object
  46207. * @returns - PBRMaterial
  46208. */
  46209. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46210. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46211. };
  46212. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46213. /**
  46214. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46215. */
  46216. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46217. /**
  46218. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46219. */
  46220. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46221. /**
  46222. * 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.
  46223. * They are also discarded below the alpha cutoff threshold to improve performances.
  46224. */
  46225. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46226. __decorate([
  46227. BABYLON.serialize(),
  46228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46229. ], PBRMaterial.prototype, "directIntensity", void 0);
  46230. __decorate([
  46231. BABYLON.serialize(),
  46232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46233. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46234. __decorate([
  46235. BABYLON.serialize(),
  46236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46237. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46238. __decorate([
  46239. BABYLON.serialize(),
  46240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46241. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46242. __decorate([
  46243. BABYLON.serialize(),
  46244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46245. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46246. __decorate([
  46247. BABYLON.serializeAsTexture(),
  46248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46249. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46250. __decorate([
  46251. BABYLON.serializeAsTexture(),
  46252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46253. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46254. __decorate([
  46255. BABYLON.serialize(),
  46256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46257. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46258. __decorate([
  46259. BABYLON.serializeAsTexture(),
  46260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46261. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46262. __decorate([
  46263. BABYLON.serializeAsTexture(),
  46264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46265. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46266. __decorate([
  46267. BABYLON.serializeAsTexture(),
  46268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46269. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46270. __decorate([
  46271. BABYLON.serializeAsTexture(),
  46272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46273. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46274. __decorate([
  46275. BABYLON.serializeAsTexture(),
  46276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46277. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46278. __decorate([
  46279. BABYLON.serialize(),
  46280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46281. ], PBRMaterial.prototype, "metallic", void 0);
  46282. __decorate([
  46283. BABYLON.serialize(),
  46284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46285. ], PBRMaterial.prototype, "roughness", void 0);
  46286. __decorate([
  46287. BABYLON.serializeAsTexture(),
  46288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46289. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46290. __decorate([
  46291. BABYLON.serializeAsTexture(),
  46292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46293. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46294. __decorate([
  46295. BABYLON.serializeAsTexture(),
  46296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46297. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46298. __decorate([
  46299. BABYLON.serializeAsTexture(),
  46300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46301. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46302. __decorate([
  46303. BABYLON.serializeAsColor3("ambient"),
  46304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46305. ], PBRMaterial.prototype, "ambientColor", void 0);
  46306. __decorate([
  46307. BABYLON.serializeAsColor3("albedo"),
  46308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46309. ], PBRMaterial.prototype, "albedoColor", void 0);
  46310. __decorate([
  46311. BABYLON.serializeAsColor3("reflectivity"),
  46312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46313. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46314. __decorate([
  46315. BABYLON.serializeAsColor3("reflection"),
  46316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46317. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46318. __decorate([
  46319. BABYLON.serializeAsColor3("emissive"),
  46320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46321. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46322. __decorate([
  46323. BABYLON.serialize(),
  46324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46325. ], PBRMaterial.prototype, "microSurface", void 0);
  46326. __decorate([
  46327. BABYLON.serialize(),
  46328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46329. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46330. __decorate([
  46331. BABYLON.serialize(),
  46332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46333. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46334. __decorate([
  46335. BABYLON.serialize(),
  46336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46337. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46338. __decorate([
  46339. BABYLON.serialize(),
  46340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46341. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46342. __decorate([
  46343. BABYLON.serialize(),
  46344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46345. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46346. __decorate([
  46347. BABYLON.serialize(),
  46348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46349. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46350. __decorate([
  46351. BABYLON.serialize(),
  46352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46353. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46354. __decorate([
  46355. BABYLON.serialize(),
  46356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46357. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46358. __decorate([
  46359. BABYLON.serialize(),
  46360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46361. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46362. __decorate([
  46363. BABYLON.serialize(),
  46364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46365. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46366. __decorate([
  46367. BABYLON.serialize(),
  46368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46369. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46370. __decorate([
  46371. BABYLON.serialize(),
  46372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46373. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46374. __decorate([
  46375. BABYLON.serialize(),
  46376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46377. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46378. __decorate([
  46379. BABYLON.serialize(),
  46380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46381. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46382. __decorate([
  46383. BABYLON.serialize(),
  46384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46385. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46386. __decorate([
  46387. BABYLON.serialize(),
  46388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46389. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46390. __decorate([
  46391. BABYLON.serialize(),
  46392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46393. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46394. __decorate([
  46395. BABYLON.serialize(),
  46396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46397. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46398. __decorate([
  46399. BABYLON.serialize(),
  46400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46401. ], PBRMaterial.prototype, "useParallax", void 0);
  46402. __decorate([
  46403. BABYLON.serialize(),
  46404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46405. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46406. __decorate([
  46407. BABYLON.serialize(),
  46408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46409. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46410. __decorate([
  46411. BABYLON.serialize(),
  46412. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46413. ], PBRMaterial.prototype, "disableLighting", void 0);
  46414. __decorate([
  46415. BABYLON.serialize(),
  46416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46417. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46418. __decorate([
  46419. BABYLON.serialize(),
  46420. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46421. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46422. __decorate([
  46423. BABYLON.serialize(),
  46424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46425. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46426. __decorate([
  46427. BABYLON.serialize(),
  46428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46429. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46430. __decorate([
  46431. BABYLON.serialize(),
  46432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46433. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46434. __decorate([
  46435. BABYLON.serialize(),
  46436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46437. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46438. __decorate([
  46439. BABYLON.serialize(),
  46440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46441. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46442. __decorate([
  46443. BABYLON.serializeAsTexture(),
  46444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46445. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46446. __decorate([
  46447. BABYLON.serialize(),
  46448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46449. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46450. __decorate([
  46451. BABYLON.serialize(),
  46452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46453. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46454. __decorate([
  46455. BABYLON.serialize(),
  46456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46457. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46458. __decorate([
  46459. BABYLON.serialize(),
  46460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46461. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46462. __decorate([
  46463. BABYLON.serialize(),
  46464. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46465. ], PBRMaterial.prototype, "unlit", void 0);
  46466. return PBRMaterial;
  46467. }(BABYLON.PBRBaseMaterial));
  46468. BABYLON.PBRMaterial = PBRMaterial;
  46469. })(BABYLON || (BABYLON = {}));
  46470. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46471. var BABYLON;
  46472. (function (BABYLON) {
  46473. /**
  46474. * The PBR material of BJS following the metal roughness convention.
  46475. *
  46476. * This fits to the PBR convention in the GLTF definition:
  46477. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46478. */
  46479. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46480. __extends(PBRMetallicRoughnessMaterial, _super);
  46481. /**
  46482. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46483. *
  46484. * @param name The material name
  46485. * @param scene The scene the material will be use in.
  46486. */
  46487. function PBRMetallicRoughnessMaterial(name, scene) {
  46488. var _this = _super.call(this, name, scene) || this;
  46489. _this._useRoughnessFromMetallicTextureAlpha = false;
  46490. _this._useRoughnessFromMetallicTextureGreen = true;
  46491. _this._useMetallnessFromMetallicTextureBlue = true;
  46492. _this.metallic = 1.0;
  46493. _this.roughness = 1.0;
  46494. return _this;
  46495. }
  46496. /**
  46497. * Return the currrent class name of the material.
  46498. */
  46499. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46500. return "PBRMetallicRoughnessMaterial";
  46501. };
  46502. /**
  46503. * Return the active textures of the material.
  46504. */
  46505. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46506. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46507. if (this.baseTexture) {
  46508. activeTextures.push(this.baseTexture);
  46509. }
  46510. if (this.metallicRoughnessTexture) {
  46511. activeTextures.push(this.metallicRoughnessTexture);
  46512. }
  46513. return activeTextures;
  46514. };
  46515. /**
  46516. * Checks to see if a texture is used in the material.
  46517. * @param texture - Base texture to use.
  46518. * @returns - Boolean specifying if a texture is used in the material.
  46519. */
  46520. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46521. if (_super.prototype.hasTexture.call(this, texture)) {
  46522. return true;
  46523. }
  46524. if (this.baseTexture === texture) {
  46525. return true;
  46526. }
  46527. if (this.metallicRoughnessTexture === texture) {
  46528. return true;
  46529. }
  46530. return false;
  46531. };
  46532. /**
  46533. * Makes a duplicate of the current material.
  46534. * @param name - name to use for the new material.
  46535. */
  46536. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46537. var _this = this;
  46538. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46539. clone.id = name;
  46540. clone.name = name;
  46541. return clone;
  46542. };
  46543. /**
  46544. * Serialize the material to a parsable JSON object.
  46545. */
  46546. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46547. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46548. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46549. return serializationObject;
  46550. };
  46551. /**
  46552. * Parses a JSON object correponding to the serialize function.
  46553. */
  46554. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46555. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46556. };
  46557. __decorate([
  46558. BABYLON.serializeAsColor3(),
  46559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46560. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46561. __decorate([
  46562. BABYLON.serializeAsTexture(),
  46563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46564. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46565. __decorate([
  46566. BABYLON.serialize(),
  46567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46568. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46569. __decorate([
  46570. BABYLON.serialize(),
  46571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46572. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46573. __decorate([
  46574. BABYLON.serializeAsTexture(),
  46575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46576. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46577. return PBRMetallicRoughnessMaterial;
  46578. }(BABYLON.PBRBaseSimpleMaterial));
  46579. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46580. })(BABYLON || (BABYLON = {}));
  46581. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46582. var BABYLON;
  46583. (function (BABYLON) {
  46584. /**
  46585. * The PBR material of BJS following the specular glossiness convention.
  46586. *
  46587. * This fits to the PBR convention in the GLTF definition:
  46588. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46589. */
  46590. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46591. __extends(PBRSpecularGlossinessMaterial, _super);
  46592. /**
  46593. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46594. *
  46595. * @param name The material name
  46596. * @param scene The scene the material will be use in.
  46597. */
  46598. function PBRSpecularGlossinessMaterial(name, scene) {
  46599. var _this = _super.call(this, name, scene) || this;
  46600. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46601. return _this;
  46602. }
  46603. /**
  46604. * Return the currrent class name of the material.
  46605. */
  46606. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46607. return "PBRSpecularGlossinessMaterial";
  46608. };
  46609. /**
  46610. * Return the active textures of the material.
  46611. */
  46612. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46613. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46614. if (this.diffuseTexture) {
  46615. activeTextures.push(this.diffuseTexture);
  46616. }
  46617. if (this.specularGlossinessTexture) {
  46618. activeTextures.push(this.specularGlossinessTexture);
  46619. }
  46620. return activeTextures;
  46621. };
  46622. /**
  46623. * Checks to see if a texture is used in the material.
  46624. * @param texture - Base texture to use.
  46625. * @returns - Boolean specifying if a texture is used in the material.
  46626. */
  46627. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46628. if (_super.prototype.hasTexture.call(this, texture)) {
  46629. return true;
  46630. }
  46631. if (this.diffuseTexture === texture) {
  46632. return true;
  46633. }
  46634. if (this.specularGlossinessTexture === texture) {
  46635. return true;
  46636. }
  46637. return false;
  46638. };
  46639. /**
  46640. * Makes a duplicate of the current material.
  46641. * @param name - name to use for the new material.
  46642. */
  46643. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46644. var _this = this;
  46645. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46646. clone.id = name;
  46647. clone.name = name;
  46648. return clone;
  46649. };
  46650. /**
  46651. * Serialize the material to a parsable JSON object.
  46652. */
  46653. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46654. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46655. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46656. return serializationObject;
  46657. };
  46658. /**
  46659. * Parses a JSON object correponding to the serialize function.
  46660. */
  46661. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46662. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46663. };
  46664. __decorate([
  46665. BABYLON.serializeAsColor3("diffuse"),
  46666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46667. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46668. __decorate([
  46669. BABYLON.serializeAsTexture(),
  46670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46671. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46672. __decorate([
  46673. BABYLON.serializeAsColor3("specular"),
  46674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46675. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46676. __decorate([
  46677. BABYLON.serialize(),
  46678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46679. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46680. __decorate([
  46681. BABYLON.serializeAsTexture(),
  46682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46683. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46684. return PBRSpecularGlossinessMaterial;
  46685. }(BABYLON.PBRBaseSimpleMaterial));
  46686. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46687. })(BABYLON || (BABYLON = {}));
  46688. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46689. var BABYLON;
  46690. (function (BABYLON) {
  46691. BABYLON.CameraInputTypes = {};
  46692. var CameraInputsManager = /** @class */ (function () {
  46693. function CameraInputsManager(camera) {
  46694. this.attached = {};
  46695. this.camera = camera;
  46696. this.checkInputs = function () { };
  46697. }
  46698. /**
  46699. * Add an input method to a camera.
  46700. * builtin inputs example: camera.inputs.addGamepad();
  46701. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46702. * @param input camera input method
  46703. */
  46704. CameraInputsManager.prototype.add = function (input) {
  46705. var type = input.getSimpleName();
  46706. if (this.attached[type]) {
  46707. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46708. return;
  46709. }
  46710. this.attached[type] = input;
  46711. input.camera = this.camera;
  46712. //for checkInputs, we are dynamically creating a function
  46713. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46714. if (input.checkInputs) {
  46715. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46716. }
  46717. if (this.attachedElement) {
  46718. input.attachControl(this.attachedElement);
  46719. }
  46720. };
  46721. /**
  46722. * Remove a specific input method from a camera
  46723. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46724. * @param inputToRemove camera input method
  46725. */
  46726. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46727. for (var cam in this.attached) {
  46728. var input = this.attached[cam];
  46729. if (input === inputToRemove) {
  46730. input.detachControl(this.attachedElement);
  46731. input.camera = null;
  46732. delete this.attached[cam];
  46733. this.rebuildInputCheck();
  46734. }
  46735. }
  46736. };
  46737. CameraInputsManager.prototype.removeByType = function (inputType) {
  46738. for (var cam in this.attached) {
  46739. var input = this.attached[cam];
  46740. if (input.getClassName() === inputType) {
  46741. input.detachControl(this.attachedElement);
  46742. input.camera = null;
  46743. delete this.attached[cam];
  46744. this.rebuildInputCheck();
  46745. }
  46746. }
  46747. };
  46748. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46749. var current = this.checkInputs;
  46750. return function () {
  46751. current();
  46752. fn();
  46753. };
  46754. };
  46755. CameraInputsManager.prototype.attachInput = function (input) {
  46756. if (this.attachedElement) {
  46757. input.attachControl(this.attachedElement, this.noPreventDefault);
  46758. }
  46759. };
  46760. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46761. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46762. if (this.attachedElement) {
  46763. return;
  46764. }
  46765. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46766. this.attachedElement = element;
  46767. this.noPreventDefault = noPreventDefault;
  46768. for (var cam in this.attached) {
  46769. this.attached[cam].attachControl(element, noPreventDefault);
  46770. }
  46771. };
  46772. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46773. if (disconnect === void 0) { disconnect = false; }
  46774. if (this.attachedElement !== element) {
  46775. return;
  46776. }
  46777. for (var cam in this.attached) {
  46778. this.attached[cam].detachControl(element);
  46779. if (disconnect) {
  46780. this.attached[cam].camera = null;
  46781. }
  46782. }
  46783. this.attachedElement = null;
  46784. };
  46785. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46786. this.checkInputs = function () { };
  46787. for (var cam in this.attached) {
  46788. var input = this.attached[cam];
  46789. if (input.checkInputs) {
  46790. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46791. }
  46792. }
  46793. };
  46794. /**
  46795. * Remove all attached input methods from a camera
  46796. */
  46797. CameraInputsManager.prototype.clear = function () {
  46798. if (this.attachedElement) {
  46799. this.detachElement(this.attachedElement, true);
  46800. }
  46801. this.attached = {};
  46802. this.attachedElement = null;
  46803. this.checkInputs = function () { };
  46804. };
  46805. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46806. var inputs = {};
  46807. for (var cam in this.attached) {
  46808. var input = this.attached[cam];
  46809. var res = BABYLON.SerializationHelper.Serialize(input);
  46810. inputs[input.getClassName()] = res;
  46811. }
  46812. serializedCamera.inputsmgr = inputs;
  46813. };
  46814. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46815. var parsedInputs = parsedCamera.inputsmgr;
  46816. if (parsedInputs) {
  46817. this.clear();
  46818. for (var n in parsedInputs) {
  46819. var construct = BABYLON.CameraInputTypes[n];
  46820. if (construct) {
  46821. var parsedinput = parsedInputs[n];
  46822. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46823. this.add(input);
  46824. }
  46825. }
  46826. }
  46827. else {
  46828. //2016-03-08 this part is for managing backward compatibility
  46829. for (var n in this.attached) {
  46830. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46831. if (construct) {
  46832. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46833. this.remove(this.attached[n]);
  46834. this.add(input);
  46835. }
  46836. }
  46837. }
  46838. };
  46839. return CameraInputsManager;
  46840. }());
  46841. BABYLON.CameraInputsManager = CameraInputsManager;
  46842. })(BABYLON || (BABYLON = {}));
  46843. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46844. var BABYLON;
  46845. (function (BABYLON) {
  46846. var TargetCamera = /** @class */ (function (_super) {
  46847. __extends(TargetCamera, _super);
  46848. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46849. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46850. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46851. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46852. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46853. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46854. _this.speed = 2.0;
  46855. _this.noRotationConstraint = false;
  46856. _this.lockedTarget = null;
  46857. _this._currentTarget = BABYLON.Vector3.Zero();
  46858. _this._viewMatrix = BABYLON.Matrix.Zero();
  46859. _this._camMatrix = BABYLON.Matrix.Zero();
  46860. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46861. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46862. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46863. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46864. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46865. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46866. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46867. return _this;
  46868. }
  46869. TargetCamera.prototype.getFrontPosition = function (distance) {
  46870. this.getWorldMatrix();
  46871. var direction = this.getTarget().subtract(this.position);
  46872. direction.normalize();
  46873. direction.scaleInPlace(distance);
  46874. return this.globalPosition.add(direction);
  46875. };
  46876. TargetCamera.prototype._getLockedTargetPosition = function () {
  46877. if (!this.lockedTarget) {
  46878. return null;
  46879. }
  46880. if (this.lockedTarget.absolutePosition) {
  46881. this.lockedTarget.computeWorldMatrix();
  46882. }
  46883. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46884. };
  46885. TargetCamera.prototype.storeState = function () {
  46886. this._storedPosition = this.position.clone();
  46887. this._storedRotation = this.rotation.clone();
  46888. if (this.rotationQuaternion) {
  46889. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46890. }
  46891. return _super.prototype.storeState.call(this);
  46892. };
  46893. /**
  46894. * Restored camera state. You must call storeState() first
  46895. */
  46896. TargetCamera.prototype._restoreStateValues = function () {
  46897. if (!_super.prototype._restoreStateValues.call(this)) {
  46898. return false;
  46899. }
  46900. this.position = this._storedPosition.clone();
  46901. this.rotation = this._storedRotation.clone();
  46902. if (this.rotationQuaternion) {
  46903. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46904. }
  46905. this.cameraDirection.copyFromFloats(0, 0, 0);
  46906. this.cameraRotation.copyFromFloats(0, 0);
  46907. return true;
  46908. };
  46909. // Cache
  46910. TargetCamera.prototype._initCache = function () {
  46911. _super.prototype._initCache.call(this);
  46912. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46913. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46914. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46915. };
  46916. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46917. if (!ignoreParentClass) {
  46918. _super.prototype._updateCache.call(this);
  46919. }
  46920. var lockedTargetPosition = this._getLockedTargetPosition();
  46921. if (!lockedTargetPosition) {
  46922. this._cache.lockedTarget = null;
  46923. }
  46924. else {
  46925. if (!this._cache.lockedTarget) {
  46926. this._cache.lockedTarget = lockedTargetPosition.clone();
  46927. }
  46928. else {
  46929. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46930. }
  46931. }
  46932. this._cache.rotation.copyFrom(this.rotation);
  46933. if (this.rotationQuaternion)
  46934. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46935. };
  46936. // Synchronized
  46937. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46938. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46939. return false;
  46940. }
  46941. var lockedTargetPosition = this._getLockedTargetPosition();
  46942. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46943. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46944. };
  46945. // Methods
  46946. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46947. var engine = this.getEngine();
  46948. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46949. };
  46950. // Target
  46951. TargetCamera.prototype.setTarget = function (target) {
  46952. this.upVector.normalize();
  46953. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46954. this._camMatrix.invert();
  46955. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46956. var vDir = target.subtract(this.position);
  46957. if (vDir.x >= 0.0) {
  46958. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46959. }
  46960. else {
  46961. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46962. }
  46963. this.rotation.z = 0;
  46964. if (isNaN(this.rotation.x)) {
  46965. this.rotation.x = 0;
  46966. }
  46967. if (isNaN(this.rotation.y)) {
  46968. this.rotation.y = 0;
  46969. }
  46970. if (isNaN(this.rotation.z)) {
  46971. this.rotation.z = 0;
  46972. }
  46973. if (this.rotationQuaternion) {
  46974. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46975. }
  46976. };
  46977. /**
  46978. * Return the current target position of the camera. This value is expressed in local space.
  46979. */
  46980. TargetCamera.prototype.getTarget = function () {
  46981. return this._currentTarget;
  46982. };
  46983. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46984. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46985. };
  46986. TargetCamera.prototype._updatePosition = function () {
  46987. if (this.parent) {
  46988. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46989. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46990. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46991. return;
  46992. }
  46993. this.position.addInPlace(this.cameraDirection);
  46994. };
  46995. TargetCamera.prototype._checkInputs = function () {
  46996. var needToMove = this._decideIfNeedsToMove();
  46997. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46998. // Move
  46999. if (needToMove) {
  47000. this._updatePosition();
  47001. }
  47002. // Rotate
  47003. if (needToRotate) {
  47004. this.rotation.x += this.cameraRotation.x;
  47005. this.rotation.y += this.cameraRotation.y;
  47006. //rotate, if quaternion is set and rotation was used
  47007. if (this.rotationQuaternion) {
  47008. var len = this.rotation.lengthSquared();
  47009. if (len) {
  47010. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47011. }
  47012. }
  47013. if (!this.noRotationConstraint) {
  47014. var limit = (Math.PI / 2) * 0.95;
  47015. if (this.rotation.x > limit)
  47016. this.rotation.x = limit;
  47017. if (this.rotation.x < -limit)
  47018. this.rotation.x = -limit;
  47019. }
  47020. }
  47021. // Inertia
  47022. if (needToMove) {
  47023. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47024. this.cameraDirection.x = 0;
  47025. }
  47026. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47027. this.cameraDirection.y = 0;
  47028. }
  47029. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47030. this.cameraDirection.z = 0;
  47031. }
  47032. this.cameraDirection.scaleInPlace(this.inertia);
  47033. }
  47034. if (needToRotate) {
  47035. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47036. this.cameraRotation.x = 0;
  47037. }
  47038. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47039. this.cameraRotation.y = 0;
  47040. }
  47041. this.cameraRotation.scaleInPlace(this.inertia);
  47042. }
  47043. _super.prototype._checkInputs.call(this);
  47044. };
  47045. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47046. if (this.rotationQuaternion) {
  47047. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47048. }
  47049. else {
  47050. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47051. }
  47052. //update the up vector!
  47053. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47054. };
  47055. TargetCamera.prototype._getViewMatrix = function () {
  47056. if (this.lockedTarget) {
  47057. this.setTarget(this._getLockedTargetPosition());
  47058. }
  47059. // Compute
  47060. this._updateCameraRotationMatrix();
  47061. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47062. // Computing target and final matrix
  47063. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47064. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47065. return this._viewMatrix;
  47066. };
  47067. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47068. if (this.parent) {
  47069. var parentWorldMatrix = this.parent.getWorldMatrix();
  47070. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47071. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47072. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47073. this._markSyncedWithParent();
  47074. }
  47075. else {
  47076. this._globalPosition.copyFrom(this.position);
  47077. this._globalCurrentTarget.copyFrom(target);
  47078. this._globalCurrentUpVector.copyFrom(up);
  47079. }
  47080. if (this.getScene().useRightHandedSystem) {
  47081. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47082. }
  47083. else {
  47084. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47085. }
  47086. };
  47087. /**
  47088. * @override
  47089. * Override Camera.createRigCamera
  47090. */
  47091. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47092. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47093. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47094. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47095. if (!this.rotationQuaternion) {
  47096. this.rotationQuaternion = new BABYLON.Quaternion();
  47097. }
  47098. rigCamera._cameraRigParams = {};
  47099. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47100. }
  47101. return rigCamera;
  47102. }
  47103. return null;
  47104. };
  47105. /**
  47106. * @override
  47107. * Override Camera._updateRigCameras
  47108. */
  47109. TargetCamera.prototype._updateRigCameras = function () {
  47110. var camLeft = this._rigCameras[0];
  47111. var camRight = this._rigCameras[1];
  47112. switch (this.cameraRigMode) {
  47113. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47114. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47115. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47116. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47117. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47118. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47119. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47120. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47121. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47122. camLeft.setTarget(this.getTarget());
  47123. camRight.setTarget(this.getTarget());
  47124. break;
  47125. case BABYLON.Camera.RIG_MODE_VR:
  47126. if (camLeft.rotationQuaternion) {
  47127. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47128. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47129. }
  47130. else {
  47131. camLeft.rotation.copyFrom(this.rotation);
  47132. camRight.rotation.copyFrom(this.rotation);
  47133. }
  47134. camLeft.position.copyFrom(this.position);
  47135. camRight.position.copyFrom(this.position);
  47136. break;
  47137. }
  47138. _super.prototype._updateRigCameras.call(this);
  47139. };
  47140. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47141. if (!this._rigCamTransformMatrix) {
  47142. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47143. }
  47144. var target = this.getTarget();
  47145. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47146. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47147. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47148. };
  47149. TargetCamera.prototype.getClassName = function () {
  47150. return "TargetCamera";
  47151. };
  47152. __decorate([
  47153. BABYLON.serializeAsVector3()
  47154. ], TargetCamera.prototype, "rotation", void 0);
  47155. __decorate([
  47156. BABYLON.serialize()
  47157. ], TargetCamera.prototype, "speed", void 0);
  47158. __decorate([
  47159. BABYLON.serializeAsMeshReference("lockedTargetId")
  47160. ], TargetCamera.prototype, "lockedTarget", void 0);
  47161. return TargetCamera;
  47162. }(BABYLON.Camera));
  47163. BABYLON.TargetCamera = TargetCamera;
  47164. })(BABYLON || (BABYLON = {}));
  47165. //# sourceMappingURL=babylon.targetCamera.js.map
  47166. var BABYLON;
  47167. (function (BABYLON) {
  47168. var FreeCameraMouseInput = /** @class */ (function () {
  47169. function FreeCameraMouseInput(touchEnabled) {
  47170. if (touchEnabled === void 0) { touchEnabled = true; }
  47171. this.touchEnabled = touchEnabled;
  47172. this.buttons = [0, 1, 2];
  47173. this.angularSensibility = 2000.0;
  47174. this.previousPosition = null;
  47175. }
  47176. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47177. var _this = this;
  47178. var engine = this.camera.getEngine();
  47179. if (!this._pointerInput) {
  47180. this._pointerInput = function (p, s) {
  47181. var evt = p.event;
  47182. if (engine.isInVRExclusivePointerMode) {
  47183. return;
  47184. }
  47185. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47186. return;
  47187. }
  47188. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47189. return;
  47190. }
  47191. var srcElement = (evt.srcElement || evt.target);
  47192. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47193. try {
  47194. srcElement.setPointerCapture(evt.pointerId);
  47195. }
  47196. catch (e) {
  47197. //Nothing to do with the error. Execution will continue.
  47198. }
  47199. _this.previousPosition = {
  47200. x: evt.clientX,
  47201. y: evt.clientY
  47202. };
  47203. if (!noPreventDefault) {
  47204. evt.preventDefault();
  47205. element.focus();
  47206. }
  47207. }
  47208. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47209. try {
  47210. srcElement.releasePointerCapture(evt.pointerId);
  47211. }
  47212. catch (e) {
  47213. //Nothing to do with the error.
  47214. }
  47215. _this.previousPosition = null;
  47216. if (!noPreventDefault) {
  47217. evt.preventDefault();
  47218. }
  47219. }
  47220. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47221. if (!_this.previousPosition || engine.isPointerLock) {
  47222. return;
  47223. }
  47224. var offsetX = evt.clientX - _this.previousPosition.x;
  47225. if (_this.camera.getScene().useRightHandedSystem)
  47226. offsetX *= -1;
  47227. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47228. offsetX *= -1;
  47229. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47230. var offsetY = evt.clientY - _this.previousPosition.y;
  47231. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47232. _this.previousPosition = {
  47233. x: evt.clientX,
  47234. y: evt.clientY
  47235. };
  47236. if (!noPreventDefault) {
  47237. evt.preventDefault();
  47238. }
  47239. }
  47240. };
  47241. }
  47242. this._onMouseMove = function (evt) {
  47243. if (!engine.isPointerLock) {
  47244. return;
  47245. }
  47246. if (engine.isInVRExclusivePointerMode) {
  47247. return;
  47248. }
  47249. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47250. if (_this.camera.getScene().useRightHandedSystem)
  47251. offsetX *= -1;
  47252. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47253. offsetX *= -1;
  47254. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47255. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47256. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47257. _this.previousPosition = null;
  47258. if (!noPreventDefault) {
  47259. evt.preventDefault();
  47260. }
  47261. };
  47262. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47263. element.addEventListener("mousemove", this._onMouseMove, false);
  47264. };
  47265. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47266. if (this._observer && element) {
  47267. this.camera.getScene().onPointerObservable.remove(this._observer);
  47268. if (this._onMouseMove) {
  47269. element.removeEventListener("mousemove", this._onMouseMove);
  47270. }
  47271. this._observer = null;
  47272. this._onMouseMove = null;
  47273. this.previousPosition = null;
  47274. }
  47275. };
  47276. FreeCameraMouseInput.prototype.getClassName = function () {
  47277. return "FreeCameraMouseInput";
  47278. };
  47279. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47280. return "mouse";
  47281. };
  47282. __decorate([
  47283. BABYLON.serialize()
  47284. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47285. __decorate([
  47286. BABYLON.serialize()
  47287. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47288. return FreeCameraMouseInput;
  47289. }());
  47290. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47291. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47292. })(BABYLON || (BABYLON = {}));
  47293. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47294. var BABYLON;
  47295. (function (BABYLON) {
  47296. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47297. function FreeCameraKeyboardMoveInput() {
  47298. this._keys = new Array();
  47299. this.keysUp = [38];
  47300. this.keysDown = [40];
  47301. this.keysLeft = [37];
  47302. this.keysRight = [39];
  47303. }
  47304. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47305. var _this = this;
  47306. if (this._onCanvasBlurObserver) {
  47307. return;
  47308. }
  47309. this._scene = this.camera.getScene();
  47310. this._engine = this._scene.getEngine();
  47311. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47312. _this._keys = [];
  47313. });
  47314. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47315. var evt = info.event;
  47316. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47317. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47318. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47319. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47320. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47321. var index = _this._keys.indexOf(evt.keyCode);
  47322. if (index === -1) {
  47323. _this._keys.push(evt.keyCode);
  47324. }
  47325. if (!noPreventDefault) {
  47326. evt.preventDefault();
  47327. }
  47328. }
  47329. }
  47330. else {
  47331. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47332. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47333. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47334. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47335. var index = _this._keys.indexOf(evt.keyCode);
  47336. if (index >= 0) {
  47337. _this._keys.splice(index, 1);
  47338. }
  47339. if (!noPreventDefault) {
  47340. evt.preventDefault();
  47341. }
  47342. }
  47343. }
  47344. });
  47345. };
  47346. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47347. if (this._scene) {
  47348. if (this._onKeyboardObserver) {
  47349. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47350. }
  47351. if (this._onCanvasBlurObserver) {
  47352. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47353. }
  47354. this._onKeyboardObserver = null;
  47355. this._onCanvasBlurObserver = null;
  47356. }
  47357. this._keys = [];
  47358. };
  47359. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47360. if (this._onKeyboardObserver) {
  47361. var camera = this.camera;
  47362. // Keyboard
  47363. for (var index = 0; index < this._keys.length; index++) {
  47364. var keyCode = this._keys[index];
  47365. var speed = camera._computeLocalCameraSpeed();
  47366. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47367. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47368. }
  47369. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47370. camera._localDirection.copyFromFloats(0, 0, speed);
  47371. }
  47372. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47373. camera._localDirection.copyFromFloats(speed, 0, 0);
  47374. }
  47375. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47376. camera._localDirection.copyFromFloats(0, 0, -speed);
  47377. }
  47378. if (camera.getScene().useRightHandedSystem) {
  47379. camera._localDirection.z *= -1;
  47380. }
  47381. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47382. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47383. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47384. }
  47385. }
  47386. };
  47387. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47388. return "FreeCameraKeyboardMoveInput";
  47389. };
  47390. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47391. this._keys = [];
  47392. };
  47393. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47394. return "keyboard";
  47395. };
  47396. __decorate([
  47397. BABYLON.serialize()
  47398. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47399. __decorate([
  47400. BABYLON.serialize()
  47401. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47402. __decorate([
  47403. BABYLON.serialize()
  47404. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47405. __decorate([
  47406. BABYLON.serialize()
  47407. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47408. return FreeCameraKeyboardMoveInput;
  47409. }());
  47410. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47411. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47412. })(BABYLON || (BABYLON = {}));
  47413. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47414. var BABYLON;
  47415. (function (BABYLON) {
  47416. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47417. __extends(FreeCameraInputsManager, _super);
  47418. function FreeCameraInputsManager(camera) {
  47419. return _super.call(this, camera) || this;
  47420. }
  47421. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47422. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47423. return this;
  47424. };
  47425. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47426. if (touchEnabled === void 0) { touchEnabled = true; }
  47427. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47428. return this;
  47429. };
  47430. FreeCameraInputsManager.prototype.addGamepad = function () {
  47431. this.add(new BABYLON.FreeCameraGamepadInput());
  47432. return this;
  47433. };
  47434. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47435. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47436. return this;
  47437. };
  47438. FreeCameraInputsManager.prototype.addTouch = function () {
  47439. this.add(new BABYLON.FreeCameraTouchInput());
  47440. return this;
  47441. };
  47442. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47443. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47444. return this;
  47445. };
  47446. return FreeCameraInputsManager;
  47447. }(BABYLON.CameraInputsManager));
  47448. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47449. })(BABYLON || (BABYLON = {}));
  47450. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47451. var BABYLON;
  47452. (function (BABYLON) {
  47453. var FreeCamera = /** @class */ (function (_super) {
  47454. __extends(FreeCamera, _super);
  47455. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47456. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47457. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47458. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47459. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47460. _this.checkCollisions = false;
  47461. _this.applyGravity = false;
  47462. _this._needMoveForGravity = false;
  47463. _this._oldPosition = BABYLON.Vector3.Zero();
  47464. _this._diffPosition = BABYLON.Vector3.Zero();
  47465. _this._newPosition = BABYLON.Vector3.Zero();
  47466. // Collisions
  47467. _this._collisionMask = -1;
  47468. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47469. if (collidedMesh === void 0) { collidedMesh = null; }
  47470. //TODO move this to the collision coordinator!
  47471. if (_this.getScene().workerCollisions)
  47472. newPosition.multiplyInPlace(_this._collider._radius);
  47473. var updatePosition = function (newPos) {
  47474. _this._newPosition.copyFrom(newPos);
  47475. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47476. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47477. _this.position.addInPlace(_this._diffPosition);
  47478. if (_this.onCollide && collidedMesh) {
  47479. _this.onCollide(collidedMesh);
  47480. }
  47481. }
  47482. };
  47483. updatePosition(newPosition);
  47484. };
  47485. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47486. _this.inputs.addKeyboard().addMouse();
  47487. return _this;
  47488. }
  47489. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47490. //-- begin properties for backward compatibility for inputs
  47491. /**
  47492. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47493. * Higher values reduce sensitivity.
  47494. */
  47495. get: function () {
  47496. var mouse = this.inputs.attached["mouse"];
  47497. if (mouse)
  47498. return mouse.angularSensibility;
  47499. return 0;
  47500. },
  47501. /**
  47502. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47503. * Higher values reduce sensitivity.
  47504. */
  47505. set: function (value) {
  47506. var mouse = this.inputs.attached["mouse"];
  47507. if (mouse)
  47508. mouse.angularSensibility = value;
  47509. },
  47510. enumerable: true,
  47511. configurable: true
  47512. });
  47513. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47514. get: function () {
  47515. var keyboard = this.inputs.attached["keyboard"];
  47516. if (keyboard)
  47517. return keyboard.keysUp;
  47518. return [];
  47519. },
  47520. set: function (value) {
  47521. var keyboard = this.inputs.attached["keyboard"];
  47522. if (keyboard)
  47523. keyboard.keysUp = value;
  47524. },
  47525. enumerable: true,
  47526. configurable: true
  47527. });
  47528. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47529. get: function () {
  47530. var keyboard = this.inputs.attached["keyboard"];
  47531. if (keyboard)
  47532. return keyboard.keysDown;
  47533. return [];
  47534. },
  47535. set: function (value) {
  47536. var keyboard = this.inputs.attached["keyboard"];
  47537. if (keyboard)
  47538. keyboard.keysDown = value;
  47539. },
  47540. enumerable: true,
  47541. configurable: true
  47542. });
  47543. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47544. get: function () {
  47545. var keyboard = this.inputs.attached["keyboard"];
  47546. if (keyboard)
  47547. return keyboard.keysLeft;
  47548. return [];
  47549. },
  47550. set: function (value) {
  47551. var keyboard = this.inputs.attached["keyboard"];
  47552. if (keyboard)
  47553. keyboard.keysLeft = value;
  47554. },
  47555. enumerable: true,
  47556. configurable: true
  47557. });
  47558. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47559. get: function () {
  47560. var keyboard = this.inputs.attached["keyboard"];
  47561. if (keyboard)
  47562. return keyboard.keysRight;
  47563. return [];
  47564. },
  47565. set: function (value) {
  47566. var keyboard = this.inputs.attached["keyboard"];
  47567. if (keyboard)
  47568. keyboard.keysRight = value;
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. // Controls
  47574. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47575. this.inputs.attachElement(element, noPreventDefault);
  47576. };
  47577. FreeCamera.prototype.detachControl = function (element) {
  47578. this.inputs.detachElement(element);
  47579. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47580. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47581. };
  47582. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47583. get: function () {
  47584. return this._collisionMask;
  47585. },
  47586. set: function (mask) {
  47587. this._collisionMask = !isNaN(mask) ? mask : -1;
  47588. },
  47589. enumerable: true,
  47590. configurable: true
  47591. });
  47592. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47593. var globalPosition;
  47594. if (this.parent) {
  47595. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47596. }
  47597. else {
  47598. globalPosition = this.position;
  47599. }
  47600. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47601. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47602. if (!this._collider) {
  47603. this._collider = new BABYLON.Collider();
  47604. }
  47605. this._collider._radius = this.ellipsoid;
  47606. this._collider.collisionMask = this._collisionMask;
  47607. //no need for clone, as long as gravity is not on.
  47608. var actualDisplacement = displacement;
  47609. //add gravity to the direction to prevent the dual-collision checking
  47610. if (this.applyGravity) {
  47611. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47612. actualDisplacement = displacement.add(this.getScene().gravity);
  47613. }
  47614. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47615. };
  47616. FreeCamera.prototype._checkInputs = function () {
  47617. if (!this._localDirection) {
  47618. this._localDirection = BABYLON.Vector3.Zero();
  47619. this._transformedDirection = BABYLON.Vector3.Zero();
  47620. }
  47621. this.inputs.checkInputs();
  47622. _super.prototype._checkInputs.call(this);
  47623. };
  47624. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47625. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47626. };
  47627. FreeCamera.prototype._updatePosition = function () {
  47628. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47629. this._collideWithWorld(this.cameraDirection);
  47630. }
  47631. else {
  47632. _super.prototype._updatePosition.call(this);
  47633. }
  47634. };
  47635. FreeCamera.prototype.dispose = function () {
  47636. this.inputs.clear();
  47637. _super.prototype.dispose.call(this);
  47638. };
  47639. FreeCamera.prototype.getClassName = function () {
  47640. return "FreeCamera";
  47641. };
  47642. __decorate([
  47643. BABYLON.serializeAsVector3()
  47644. ], FreeCamera.prototype, "ellipsoid", void 0);
  47645. __decorate([
  47646. BABYLON.serializeAsVector3()
  47647. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47648. __decorate([
  47649. BABYLON.serialize()
  47650. ], FreeCamera.prototype, "checkCollisions", void 0);
  47651. __decorate([
  47652. BABYLON.serialize()
  47653. ], FreeCamera.prototype, "applyGravity", void 0);
  47654. return FreeCamera;
  47655. }(BABYLON.TargetCamera));
  47656. BABYLON.FreeCamera = FreeCamera;
  47657. })(BABYLON || (BABYLON = {}));
  47658. //# sourceMappingURL=babylon.freeCamera.js.map
  47659. var BABYLON;
  47660. (function (BABYLON) {
  47661. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47662. function ArcRotateCameraKeyboardMoveInput() {
  47663. this._keys = new Array();
  47664. this.keysUp = [38];
  47665. this.keysDown = [40];
  47666. this.keysLeft = [37];
  47667. this.keysRight = [39];
  47668. this.keysReset = [220];
  47669. this.panningSensibility = 50.0;
  47670. this.zoomingSensibility = 25.0;
  47671. this.useAltToZoom = true;
  47672. }
  47673. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47674. var _this = this;
  47675. if (this._onCanvasBlurObserver) {
  47676. return;
  47677. }
  47678. this._scene = this.camera.getScene();
  47679. this._engine = this._scene.getEngine();
  47680. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47681. _this._keys = [];
  47682. });
  47683. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47684. var evt = info.event;
  47685. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47686. _this._ctrlPressed = evt.ctrlKey;
  47687. _this._altPressed = evt.altKey;
  47688. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47689. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47690. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47691. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47692. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47693. var index = _this._keys.indexOf(evt.keyCode);
  47694. if (index === -1) {
  47695. _this._keys.push(evt.keyCode);
  47696. }
  47697. if (evt.preventDefault) {
  47698. if (!noPreventDefault) {
  47699. evt.preventDefault();
  47700. }
  47701. }
  47702. }
  47703. }
  47704. else {
  47705. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47706. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47707. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47708. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47709. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47710. var index = _this._keys.indexOf(evt.keyCode);
  47711. if (index >= 0) {
  47712. _this._keys.splice(index, 1);
  47713. }
  47714. if (evt.preventDefault) {
  47715. if (!noPreventDefault) {
  47716. evt.preventDefault();
  47717. }
  47718. }
  47719. }
  47720. }
  47721. });
  47722. };
  47723. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47724. if (this._scene) {
  47725. if (this._onKeyboardObserver) {
  47726. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47727. }
  47728. if (this._onCanvasBlurObserver) {
  47729. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47730. }
  47731. this._onKeyboardObserver = null;
  47732. this._onCanvasBlurObserver = null;
  47733. }
  47734. this._keys = [];
  47735. };
  47736. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47737. if (this._onKeyboardObserver) {
  47738. var camera = this.camera;
  47739. for (var index = 0; index < this._keys.length; index++) {
  47740. var keyCode = this._keys[index];
  47741. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47742. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47743. camera.inertialPanningX -= 1 / this.panningSensibility;
  47744. }
  47745. else {
  47746. camera.inertialAlphaOffset -= 0.01;
  47747. }
  47748. }
  47749. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47750. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47751. camera.inertialPanningY += 1 / this.panningSensibility;
  47752. }
  47753. else if (this._altPressed && this.useAltToZoom) {
  47754. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47755. }
  47756. else {
  47757. camera.inertialBetaOffset -= 0.01;
  47758. }
  47759. }
  47760. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47761. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47762. camera.inertialPanningX += 1 / this.panningSensibility;
  47763. }
  47764. else {
  47765. camera.inertialAlphaOffset += 0.01;
  47766. }
  47767. }
  47768. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47769. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47770. camera.inertialPanningY -= 1 / this.panningSensibility;
  47771. }
  47772. else if (this._altPressed && this.useAltToZoom) {
  47773. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47774. }
  47775. else {
  47776. camera.inertialBetaOffset += 0.01;
  47777. }
  47778. }
  47779. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47780. camera.restoreState();
  47781. }
  47782. }
  47783. }
  47784. };
  47785. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47786. return "ArcRotateCameraKeyboardMoveInput";
  47787. };
  47788. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47789. return "keyboard";
  47790. };
  47791. __decorate([
  47792. BABYLON.serialize()
  47793. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47794. __decorate([
  47795. BABYLON.serialize()
  47796. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47797. __decorate([
  47798. BABYLON.serialize()
  47799. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47800. __decorate([
  47801. BABYLON.serialize()
  47802. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47803. __decorate([
  47804. BABYLON.serialize()
  47805. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47806. __decorate([
  47807. BABYLON.serialize()
  47808. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47809. __decorate([
  47810. BABYLON.serialize()
  47811. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47812. __decorate([
  47813. BABYLON.serialize()
  47814. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47815. return ArcRotateCameraKeyboardMoveInput;
  47816. }());
  47817. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47818. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47819. })(BABYLON || (BABYLON = {}));
  47820. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47821. var BABYLON;
  47822. (function (BABYLON) {
  47823. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47824. function ArcRotateCameraMouseWheelInput() {
  47825. this.wheelPrecision = 3.0;
  47826. /**
  47827. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47828. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47829. */
  47830. this.wheelDeltaPercentage = 0;
  47831. }
  47832. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47833. var _this = this;
  47834. this._wheel = function (p, s) {
  47835. //sanity check - this should be a PointerWheel event.
  47836. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47837. return;
  47838. var event = p.event;
  47839. var delta = 0;
  47840. if (event.wheelDelta) {
  47841. if (_this.wheelDeltaPercentage) {
  47842. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47843. if (event.wheelDelta > 0) {
  47844. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47845. }
  47846. else {
  47847. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47848. }
  47849. }
  47850. else {
  47851. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47852. }
  47853. }
  47854. else if (event.detail) {
  47855. delta = -event.detail / _this.wheelPrecision;
  47856. }
  47857. if (delta)
  47858. _this.camera.inertialRadiusOffset += delta;
  47859. if (event.preventDefault) {
  47860. if (!noPreventDefault) {
  47861. event.preventDefault();
  47862. }
  47863. }
  47864. };
  47865. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47866. };
  47867. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47868. if (this._observer && element) {
  47869. this.camera.getScene().onPointerObservable.remove(this._observer);
  47870. this._observer = null;
  47871. this._wheel = null;
  47872. }
  47873. };
  47874. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47875. return "ArcRotateCameraMouseWheelInput";
  47876. };
  47877. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47878. return "mousewheel";
  47879. };
  47880. __decorate([
  47881. BABYLON.serialize()
  47882. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47883. __decorate([
  47884. BABYLON.serialize()
  47885. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47886. return ArcRotateCameraMouseWheelInput;
  47887. }());
  47888. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47889. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47890. })(BABYLON || (BABYLON = {}));
  47891. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47892. var BABYLON;
  47893. (function (BABYLON) {
  47894. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47895. function ArcRotateCameraPointersInput() {
  47896. this.buttons = [0, 1, 2];
  47897. this.angularSensibilityX = 1000.0;
  47898. this.angularSensibilityY = 1000.0;
  47899. this.pinchPrecision = 12.0;
  47900. /**
  47901. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47902. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47903. */
  47904. this.pinchDeltaPercentage = 0;
  47905. this.panningSensibility = 1000.0;
  47906. this.multiTouchPanning = true;
  47907. this.multiTouchPanAndZoom = true;
  47908. this._isPanClick = false;
  47909. this.pinchInwards = true;
  47910. }
  47911. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47912. var _this = this;
  47913. var engine = this.camera.getEngine();
  47914. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47915. var pointA = null;
  47916. var pointB = null;
  47917. var previousPinchSquaredDistance = 0;
  47918. var initialDistance = 0;
  47919. var twoFingerActivityCount = 0;
  47920. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47921. this._pointerInput = function (p, s) {
  47922. var evt = p.event;
  47923. var isTouch = p.event.pointerType === "touch";
  47924. if (engine.isInVRExclusivePointerMode) {
  47925. return;
  47926. }
  47927. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47928. return;
  47929. }
  47930. var srcElement = (evt.srcElement || evt.target);
  47931. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47932. try {
  47933. srcElement.setPointerCapture(evt.pointerId);
  47934. }
  47935. catch (e) {
  47936. //Nothing to do with the error. Execution will continue.
  47937. }
  47938. // Manage panning with pan button click
  47939. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47940. // manage pointers
  47941. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47942. if (pointA === null) {
  47943. pointA = cacheSoloPointer;
  47944. }
  47945. else if (pointB === null) {
  47946. pointB = cacheSoloPointer;
  47947. }
  47948. if (!noPreventDefault) {
  47949. evt.preventDefault();
  47950. element.focus();
  47951. }
  47952. }
  47953. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47954. _this.camera.restoreState();
  47955. }
  47956. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47957. try {
  47958. srcElement.releasePointerCapture(evt.pointerId);
  47959. }
  47960. catch (e) {
  47961. //Nothing to do with the error.
  47962. }
  47963. cacheSoloPointer = null;
  47964. previousPinchSquaredDistance = 0;
  47965. previousMultiTouchPanPosition.isPaning = false;
  47966. previousMultiTouchPanPosition.isPinching = false;
  47967. twoFingerActivityCount = 0;
  47968. initialDistance = 0;
  47969. if (!isTouch) {
  47970. pointB = null; // Mouse and pen are mono pointer
  47971. }
  47972. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47973. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47974. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47975. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47976. if (engine._badOS) {
  47977. pointA = pointB = null;
  47978. }
  47979. else {
  47980. //only remove the impacted pointer in case of multitouch allowing on most
  47981. //platforms switching from rotate to zoom and pan seamlessly.
  47982. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47983. pointA = pointB;
  47984. pointB = null;
  47985. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47986. }
  47987. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47988. pointB = null;
  47989. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47990. }
  47991. else {
  47992. pointA = pointB = null;
  47993. }
  47994. }
  47995. if (!noPreventDefault) {
  47996. evt.preventDefault();
  47997. }
  47998. }
  47999. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48000. if (!noPreventDefault) {
  48001. evt.preventDefault();
  48002. }
  48003. // One button down
  48004. if (pointA && pointB === null && cacheSoloPointer) {
  48005. if (_this.panningSensibility !== 0 &&
  48006. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48007. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48008. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48009. }
  48010. else {
  48011. var offsetX = evt.clientX - cacheSoloPointer.x;
  48012. var offsetY = evt.clientY - cacheSoloPointer.y;
  48013. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48014. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48015. }
  48016. cacheSoloPointer.x = evt.clientX;
  48017. cacheSoloPointer.y = evt.clientY;
  48018. }
  48019. // Two buttons down: pinch/pan
  48020. else if (pointA && pointB) {
  48021. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48022. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48023. ed.x = evt.clientX;
  48024. ed.y = evt.clientY;
  48025. var direction = _this.pinchInwards ? 1 : -1;
  48026. var distX = pointA.x - pointB.x;
  48027. var distY = pointA.y - pointB.y;
  48028. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48029. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48030. if (previousPinchSquaredDistance === 0) {
  48031. initialDistance = pinchDistance;
  48032. previousPinchSquaredDistance = pinchSquaredDistance;
  48033. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48034. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48035. return;
  48036. }
  48037. if (_this.multiTouchPanAndZoom) {
  48038. if (_this.pinchDeltaPercentage) {
  48039. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48040. }
  48041. else {
  48042. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48043. (_this.pinchPrecision *
  48044. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48045. direction);
  48046. }
  48047. if (_this.panningSensibility !== 0) {
  48048. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48049. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48050. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48051. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48052. previousMultiTouchPanPosition.x = pointersCenterX;
  48053. previousMultiTouchPanPosition.y = pointersCenterY;
  48054. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48055. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48056. }
  48057. }
  48058. else {
  48059. twoFingerActivityCount++;
  48060. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48061. if (_this.pinchDeltaPercentage) {
  48062. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48063. }
  48064. else {
  48065. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48066. (_this.pinchPrecision *
  48067. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48068. direction);
  48069. }
  48070. previousMultiTouchPanPosition.isPaning = false;
  48071. previousMultiTouchPanPosition.isPinching = true;
  48072. }
  48073. else {
  48074. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48075. if (!previousMultiTouchPanPosition.isPaning) {
  48076. previousMultiTouchPanPosition.isPaning = true;
  48077. previousMultiTouchPanPosition.isPinching = false;
  48078. previousMultiTouchPanPosition.x = ed.x;
  48079. previousMultiTouchPanPosition.y = ed.y;
  48080. return;
  48081. }
  48082. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48083. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48084. }
  48085. }
  48086. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48087. previousMultiTouchPanPosition.x = ed.x;
  48088. previousMultiTouchPanPosition.y = ed.y;
  48089. }
  48090. }
  48091. previousPinchSquaredDistance = pinchSquaredDistance;
  48092. }
  48093. }
  48094. };
  48095. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48096. this._onContextMenu = function (evt) {
  48097. evt.preventDefault();
  48098. };
  48099. if (!this.camera._useCtrlForPanning) {
  48100. element.addEventListener("contextmenu", this._onContextMenu, false);
  48101. }
  48102. this._onLostFocus = function () {
  48103. //this._keys = [];
  48104. pointA = pointB = null;
  48105. previousPinchSquaredDistance = 0;
  48106. previousMultiTouchPanPosition.isPaning = false;
  48107. previousMultiTouchPanPosition.isPinching = false;
  48108. twoFingerActivityCount = 0;
  48109. cacheSoloPointer = null;
  48110. initialDistance = 0;
  48111. };
  48112. this._onMouseMove = function (evt) {
  48113. if (!engine.isPointerLock) {
  48114. return;
  48115. }
  48116. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48117. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48118. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48119. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48120. if (!noPreventDefault) {
  48121. evt.preventDefault();
  48122. }
  48123. };
  48124. this._onGestureStart = function (e) {
  48125. if (window.MSGesture === undefined) {
  48126. return;
  48127. }
  48128. if (!_this._MSGestureHandler) {
  48129. _this._MSGestureHandler = new MSGesture();
  48130. _this._MSGestureHandler.target = element;
  48131. }
  48132. _this._MSGestureHandler.addPointer(e.pointerId);
  48133. };
  48134. this._onGesture = function (e) {
  48135. _this.camera.radius *= e.scale;
  48136. if (e.preventDefault) {
  48137. if (!noPreventDefault) {
  48138. e.stopPropagation();
  48139. e.preventDefault();
  48140. }
  48141. }
  48142. };
  48143. element.addEventListener("mousemove", this._onMouseMove, false);
  48144. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48145. element.addEventListener("MSGestureChange", this._onGesture, false);
  48146. BABYLON.Tools.RegisterTopRootEvents([
  48147. { name: "blur", handler: this._onLostFocus }
  48148. ]);
  48149. };
  48150. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48151. if (this._onLostFocus) {
  48152. BABYLON.Tools.UnregisterTopRootEvents([
  48153. { name: "blur", handler: this._onLostFocus }
  48154. ]);
  48155. }
  48156. if (element && this._observer) {
  48157. this.camera.getScene().onPointerObservable.remove(this._observer);
  48158. this._observer = null;
  48159. if (this._onContextMenu) {
  48160. element.removeEventListener("contextmenu", this._onContextMenu);
  48161. }
  48162. if (this._onMouseMove) {
  48163. element.removeEventListener("mousemove", this._onMouseMove);
  48164. }
  48165. if (this._onGestureStart) {
  48166. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48167. }
  48168. if (this._onGesture) {
  48169. element.removeEventListener("MSGestureChange", this._onGesture);
  48170. }
  48171. this._isPanClick = false;
  48172. this.pinchInwards = true;
  48173. this._onMouseMove = null;
  48174. this._onGestureStart = null;
  48175. this._onGesture = null;
  48176. this._MSGestureHandler = null;
  48177. this._onLostFocus = null;
  48178. this._onContextMenu = null;
  48179. }
  48180. };
  48181. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48182. return "ArcRotateCameraPointersInput";
  48183. };
  48184. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48185. return "pointers";
  48186. };
  48187. __decorate([
  48188. BABYLON.serialize()
  48189. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48190. __decorate([
  48191. BABYLON.serialize()
  48192. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48193. __decorate([
  48194. BABYLON.serialize()
  48195. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48196. __decorate([
  48197. BABYLON.serialize()
  48198. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48199. __decorate([
  48200. BABYLON.serialize()
  48201. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48202. __decorate([
  48203. BABYLON.serialize()
  48204. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48205. __decorate([
  48206. BABYLON.serialize()
  48207. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48208. __decorate([
  48209. BABYLON.serialize()
  48210. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48211. return ArcRotateCameraPointersInput;
  48212. }());
  48213. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48214. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48215. })(BABYLON || (BABYLON = {}));
  48216. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48217. var BABYLON;
  48218. (function (BABYLON) {
  48219. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48220. __extends(ArcRotateCameraInputsManager, _super);
  48221. function ArcRotateCameraInputsManager(camera) {
  48222. return _super.call(this, camera) || this;
  48223. }
  48224. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48225. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48226. return this;
  48227. };
  48228. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48229. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48230. return this;
  48231. };
  48232. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48233. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48234. return this;
  48235. };
  48236. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48237. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48238. return this;
  48239. };
  48240. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48241. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48242. return this;
  48243. };
  48244. return ArcRotateCameraInputsManager;
  48245. }(BABYLON.CameraInputsManager));
  48246. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48247. })(BABYLON || (BABYLON = {}));
  48248. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48249. var BABYLON;
  48250. (function (BABYLON) {
  48251. var ArcRotateCamera = /** @class */ (function (_super) {
  48252. __extends(ArcRotateCamera, _super);
  48253. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48254. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48255. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48256. _this.inertialAlphaOffset = 0;
  48257. _this.inertialBetaOffset = 0;
  48258. _this.inertialRadiusOffset = 0;
  48259. _this.lowerAlphaLimit = null;
  48260. _this.upperAlphaLimit = null;
  48261. _this.lowerBetaLimit = 0.01;
  48262. _this.upperBetaLimit = Math.PI;
  48263. _this.lowerRadiusLimit = null;
  48264. _this.upperRadiusLimit = null;
  48265. _this.inertialPanningX = 0;
  48266. _this.inertialPanningY = 0;
  48267. _this.pinchToPanMaxDistance = 20;
  48268. _this.panningDistanceLimit = null;
  48269. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48270. _this.panningInertia = 0.9;
  48271. //-- end properties for backward compatibility for inputs
  48272. _this.zoomOnFactor = 1;
  48273. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48274. _this.allowUpsideDown = true;
  48275. _this._viewMatrix = new BABYLON.Matrix();
  48276. // Panning
  48277. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48278. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48279. _this.checkCollisions = false;
  48280. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48281. _this._previousPosition = BABYLON.Vector3.Zero();
  48282. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48283. _this._newPosition = BABYLON.Vector3.Zero();
  48284. _this._computationVector = BABYLON.Vector3.Zero();
  48285. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48286. if (collidedMesh === void 0) { collidedMesh = null; }
  48287. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48288. newPosition.multiplyInPlace(_this._collider._radius);
  48289. }
  48290. if (!collidedMesh) {
  48291. _this._previousPosition.copyFrom(_this.position);
  48292. }
  48293. else {
  48294. _this.setPosition(newPosition);
  48295. if (_this.onCollide) {
  48296. _this.onCollide(collidedMesh);
  48297. }
  48298. }
  48299. // Recompute because of constraints
  48300. var cosa = Math.cos(_this.alpha);
  48301. var sina = Math.sin(_this.alpha);
  48302. var cosb = Math.cos(_this.beta);
  48303. var sinb = Math.sin(_this.beta);
  48304. if (sinb === 0) {
  48305. sinb = 0.0001;
  48306. }
  48307. var target = _this._getTargetPosition();
  48308. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48309. target.addToRef(_this._computationVector, _this._newPosition);
  48310. _this.position.copyFrom(_this._newPosition);
  48311. var up = _this.upVector;
  48312. if (_this.allowUpsideDown && _this.beta < 0) {
  48313. up = up.clone();
  48314. up = up.negate();
  48315. }
  48316. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48317. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48318. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48319. _this._collisionTriggered = false;
  48320. };
  48321. _this._target = BABYLON.Vector3.Zero();
  48322. if (target) {
  48323. _this.setTarget(target);
  48324. }
  48325. _this.alpha = alpha;
  48326. _this.beta = beta;
  48327. _this.radius = radius;
  48328. _this.getViewMatrix();
  48329. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48330. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48331. return _this;
  48332. }
  48333. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48334. get: function () {
  48335. return this._target;
  48336. },
  48337. set: function (value) {
  48338. this.setTarget(value);
  48339. },
  48340. enumerable: true,
  48341. configurable: true
  48342. });
  48343. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48344. //-- begin properties for backward compatibility for inputs
  48345. get: function () {
  48346. var pointers = this.inputs.attached["pointers"];
  48347. if (pointers)
  48348. return pointers.angularSensibilityX;
  48349. return 0;
  48350. },
  48351. set: function (value) {
  48352. var pointers = this.inputs.attached["pointers"];
  48353. if (pointers) {
  48354. pointers.angularSensibilityX = value;
  48355. }
  48356. },
  48357. enumerable: true,
  48358. configurable: true
  48359. });
  48360. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48361. get: function () {
  48362. var pointers = this.inputs.attached["pointers"];
  48363. if (pointers)
  48364. return pointers.angularSensibilityY;
  48365. return 0;
  48366. },
  48367. set: function (value) {
  48368. var pointers = this.inputs.attached["pointers"];
  48369. if (pointers) {
  48370. pointers.angularSensibilityY = value;
  48371. }
  48372. },
  48373. enumerable: true,
  48374. configurable: true
  48375. });
  48376. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48377. get: function () {
  48378. var pointers = this.inputs.attached["pointers"];
  48379. if (pointers)
  48380. return pointers.pinchPrecision;
  48381. return 0;
  48382. },
  48383. set: function (value) {
  48384. var pointers = this.inputs.attached["pointers"];
  48385. if (pointers) {
  48386. pointers.pinchPrecision = value;
  48387. }
  48388. },
  48389. enumerable: true,
  48390. configurable: true
  48391. });
  48392. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48393. get: function () {
  48394. var pointers = this.inputs.attached["pointers"];
  48395. if (pointers)
  48396. return pointers.pinchDeltaPercentage;
  48397. return 0;
  48398. },
  48399. set: function (value) {
  48400. var pointers = this.inputs.attached["pointers"];
  48401. if (pointers) {
  48402. pointers.pinchDeltaPercentage = value;
  48403. }
  48404. },
  48405. enumerable: true,
  48406. configurable: true
  48407. });
  48408. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48409. get: function () {
  48410. var pointers = this.inputs.attached["pointers"];
  48411. if (pointers)
  48412. return pointers.panningSensibility;
  48413. return 0;
  48414. },
  48415. set: function (value) {
  48416. var pointers = this.inputs.attached["pointers"];
  48417. if (pointers) {
  48418. pointers.panningSensibility = value;
  48419. }
  48420. },
  48421. enumerable: true,
  48422. configurable: true
  48423. });
  48424. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48425. get: function () {
  48426. var keyboard = this.inputs.attached["keyboard"];
  48427. if (keyboard)
  48428. return keyboard.keysUp;
  48429. return [];
  48430. },
  48431. set: function (value) {
  48432. var keyboard = this.inputs.attached["keyboard"];
  48433. if (keyboard)
  48434. keyboard.keysUp = value;
  48435. },
  48436. enumerable: true,
  48437. configurable: true
  48438. });
  48439. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48440. get: function () {
  48441. var keyboard = this.inputs.attached["keyboard"];
  48442. if (keyboard)
  48443. return keyboard.keysDown;
  48444. return [];
  48445. },
  48446. set: function (value) {
  48447. var keyboard = this.inputs.attached["keyboard"];
  48448. if (keyboard)
  48449. keyboard.keysDown = value;
  48450. },
  48451. enumerable: true,
  48452. configurable: true
  48453. });
  48454. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48455. get: function () {
  48456. var keyboard = this.inputs.attached["keyboard"];
  48457. if (keyboard)
  48458. return keyboard.keysLeft;
  48459. return [];
  48460. },
  48461. set: function (value) {
  48462. var keyboard = this.inputs.attached["keyboard"];
  48463. if (keyboard)
  48464. keyboard.keysLeft = value;
  48465. },
  48466. enumerable: true,
  48467. configurable: true
  48468. });
  48469. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48470. get: function () {
  48471. var keyboard = this.inputs.attached["keyboard"];
  48472. if (keyboard)
  48473. return keyboard.keysRight;
  48474. return [];
  48475. },
  48476. set: function (value) {
  48477. var keyboard = this.inputs.attached["keyboard"];
  48478. if (keyboard)
  48479. keyboard.keysRight = value;
  48480. },
  48481. enumerable: true,
  48482. configurable: true
  48483. });
  48484. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48485. get: function () {
  48486. var mousewheel = this.inputs.attached["mousewheel"];
  48487. if (mousewheel)
  48488. return mousewheel.wheelPrecision;
  48489. return 0;
  48490. },
  48491. set: function (value) {
  48492. var mousewheel = this.inputs.attached["mousewheel"];
  48493. if (mousewheel)
  48494. mousewheel.wheelPrecision = value;
  48495. },
  48496. enumerable: true,
  48497. configurable: true
  48498. });
  48499. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48500. get: function () {
  48501. var mousewheel = this.inputs.attached["mousewheel"];
  48502. if (mousewheel)
  48503. return mousewheel.wheelDeltaPercentage;
  48504. return 0;
  48505. },
  48506. set: function (value) {
  48507. var mousewheel = this.inputs.attached["mousewheel"];
  48508. if (mousewheel)
  48509. mousewheel.wheelDeltaPercentage = value;
  48510. },
  48511. enumerable: true,
  48512. configurable: true
  48513. });
  48514. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48515. get: function () {
  48516. return this._bouncingBehavior;
  48517. },
  48518. enumerable: true,
  48519. configurable: true
  48520. });
  48521. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48522. get: function () {
  48523. return this._bouncingBehavior != null;
  48524. },
  48525. set: function (value) {
  48526. if (value === this.useBouncingBehavior) {
  48527. return;
  48528. }
  48529. if (value) {
  48530. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48531. this.addBehavior(this._bouncingBehavior);
  48532. }
  48533. else if (this._bouncingBehavior) {
  48534. this.removeBehavior(this._bouncingBehavior);
  48535. this._bouncingBehavior = null;
  48536. }
  48537. },
  48538. enumerable: true,
  48539. configurable: true
  48540. });
  48541. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48542. get: function () {
  48543. return this._framingBehavior;
  48544. },
  48545. enumerable: true,
  48546. configurable: true
  48547. });
  48548. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48549. get: function () {
  48550. return this._framingBehavior != null;
  48551. },
  48552. set: function (value) {
  48553. if (value === this.useFramingBehavior) {
  48554. return;
  48555. }
  48556. if (value) {
  48557. this._framingBehavior = new BABYLON.FramingBehavior();
  48558. this.addBehavior(this._framingBehavior);
  48559. }
  48560. else if (this._framingBehavior) {
  48561. this.removeBehavior(this._framingBehavior);
  48562. this._framingBehavior = null;
  48563. }
  48564. },
  48565. enumerable: true,
  48566. configurable: true
  48567. });
  48568. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48569. get: function () {
  48570. return this._autoRotationBehavior;
  48571. },
  48572. enumerable: true,
  48573. configurable: true
  48574. });
  48575. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48576. get: function () {
  48577. return this._autoRotationBehavior != null;
  48578. },
  48579. set: function (value) {
  48580. if (value === this.useAutoRotationBehavior) {
  48581. return;
  48582. }
  48583. if (value) {
  48584. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48585. this.addBehavior(this._autoRotationBehavior);
  48586. }
  48587. else if (this._autoRotationBehavior) {
  48588. this.removeBehavior(this._autoRotationBehavior);
  48589. this._autoRotationBehavior = null;
  48590. }
  48591. },
  48592. enumerable: true,
  48593. configurable: true
  48594. });
  48595. // Cache
  48596. ArcRotateCamera.prototype._initCache = function () {
  48597. _super.prototype._initCache.call(this);
  48598. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48599. this._cache.alpha = undefined;
  48600. this._cache.beta = undefined;
  48601. this._cache.radius = undefined;
  48602. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48603. };
  48604. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48605. if (!ignoreParentClass) {
  48606. _super.prototype._updateCache.call(this);
  48607. }
  48608. this._cache._target.copyFrom(this._getTargetPosition());
  48609. this._cache.alpha = this.alpha;
  48610. this._cache.beta = this.beta;
  48611. this._cache.radius = this.radius;
  48612. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48613. };
  48614. ArcRotateCamera.prototype._getTargetPosition = function () {
  48615. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48616. var pos = this._targetHost.getAbsolutePosition();
  48617. if (this._targetBoundingCenter) {
  48618. pos.addToRef(this._targetBoundingCenter, this._target);
  48619. }
  48620. else {
  48621. this._target.copyFrom(pos);
  48622. }
  48623. }
  48624. var lockedTargetPosition = this._getLockedTargetPosition();
  48625. if (lockedTargetPosition) {
  48626. return lockedTargetPosition;
  48627. }
  48628. return this._target;
  48629. };
  48630. ArcRotateCamera.prototype.storeState = function () {
  48631. this._storedAlpha = this.alpha;
  48632. this._storedBeta = this.beta;
  48633. this._storedRadius = this.radius;
  48634. this._storedTarget = this._getTargetPosition().clone();
  48635. return _super.prototype.storeState.call(this);
  48636. };
  48637. /**
  48638. * Restored camera state. You must call storeState() first
  48639. */
  48640. ArcRotateCamera.prototype._restoreStateValues = function () {
  48641. if (!_super.prototype._restoreStateValues.call(this)) {
  48642. return false;
  48643. }
  48644. this.alpha = this._storedAlpha;
  48645. this.beta = this._storedBeta;
  48646. this.radius = this._storedRadius;
  48647. this.setTarget(this._storedTarget.clone());
  48648. this.inertialAlphaOffset = 0;
  48649. this.inertialBetaOffset = 0;
  48650. this.inertialRadiusOffset = 0;
  48651. this.inertialPanningX = 0;
  48652. this.inertialPanningY = 0;
  48653. return true;
  48654. };
  48655. // Synchronized
  48656. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48657. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48658. return false;
  48659. return this._cache._target.equals(this._getTargetPosition())
  48660. && this._cache.alpha === this.alpha
  48661. && this._cache.beta === this.beta
  48662. && this._cache.radius === this.radius
  48663. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48664. };
  48665. // Methods
  48666. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48667. var _this = this;
  48668. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48669. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48670. this._useCtrlForPanning = useCtrlForPanning;
  48671. this._panningMouseButton = panningMouseButton;
  48672. this.inputs.attachElement(element, noPreventDefault);
  48673. this._reset = function () {
  48674. _this.inertialAlphaOffset = 0;
  48675. _this.inertialBetaOffset = 0;
  48676. _this.inertialRadiusOffset = 0;
  48677. _this.inertialPanningX = 0;
  48678. _this.inertialPanningY = 0;
  48679. };
  48680. };
  48681. ArcRotateCamera.prototype.detachControl = function (element) {
  48682. this.inputs.detachElement(element);
  48683. if (this._reset) {
  48684. this._reset();
  48685. }
  48686. };
  48687. ArcRotateCamera.prototype._checkInputs = function () {
  48688. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48689. if (this._collisionTriggered) {
  48690. return;
  48691. }
  48692. this.inputs.checkInputs();
  48693. // Inertia
  48694. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48695. var inertialAlphaOffset = this.inertialAlphaOffset;
  48696. if (this.beta <= 0)
  48697. inertialAlphaOffset *= -1;
  48698. if (this.getScene().useRightHandedSystem)
  48699. inertialAlphaOffset *= -1;
  48700. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48701. inertialAlphaOffset *= -1;
  48702. this.alpha += inertialAlphaOffset;
  48703. this.beta += this.inertialBetaOffset;
  48704. this.radius -= this.inertialRadiusOffset;
  48705. this.inertialAlphaOffset *= this.inertia;
  48706. this.inertialBetaOffset *= this.inertia;
  48707. this.inertialRadiusOffset *= this.inertia;
  48708. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48709. this.inertialAlphaOffset = 0;
  48710. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48711. this.inertialBetaOffset = 0;
  48712. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48713. this.inertialRadiusOffset = 0;
  48714. }
  48715. // Panning inertia
  48716. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48717. if (!this._localDirection) {
  48718. this._localDirection = BABYLON.Vector3.Zero();
  48719. this._transformedDirection = BABYLON.Vector3.Zero();
  48720. }
  48721. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48722. this._localDirection.multiplyInPlace(this.panningAxis);
  48723. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48724. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48725. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48726. if (!this.panningAxis.y) {
  48727. this._transformedDirection.y = 0;
  48728. }
  48729. if (!this._targetHost) {
  48730. if (this.panningDistanceLimit) {
  48731. this._transformedDirection.addInPlace(this._target);
  48732. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48733. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48734. this._target.copyFrom(this._transformedDirection);
  48735. }
  48736. }
  48737. else {
  48738. this._target.addInPlace(this._transformedDirection);
  48739. }
  48740. }
  48741. this.inertialPanningX *= this.panningInertia;
  48742. this.inertialPanningY *= this.panningInertia;
  48743. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48744. this.inertialPanningX = 0;
  48745. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48746. this.inertialPanningY = 0;
  48747. }
  48748. // Limits
  48749. this._checkLimits();
  48750. _super.prototype._checkInputs.call(this);
  48751. };
  48752. ArcRotateCamera.prototype._checkLimits = function () {
  48753. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48754. if (this.allowUpsideDown && this.beta > Math.PI) {
  48755. this.beta = this.beta - (2 * Math.PI);
  48756. }
  48757. }
  48758. else {
  48759. if (this.beta < this.lowerBetaLimit) {
  48760. this.beta = this.lowerBetaLimit;
  48761. }
  48762. }
  48763. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48764. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48765. this.beta = this.beta + (2 * Math.PI);
  48766. }
  48767. }
  48768. else {
  48769. if (this.beta > this.upperBetaLimit) {
  48770. this.beta = this.upperBetaLimit;
  48771. }
  48772. }
  48773. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48774. this.alpha = this.lowerAlphaLimit;
  48775. }
  48776. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48777. this.alpha = this.upperAlphaLimit;
  48778. }
  48779. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48780. this.radius = this.lowerRadiusLimit;
  48781. }
  48782. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48783. this.radius = this.upperRadiusLimit;
  48784. }
  48785. };
  48786. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48787. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48788. this.radius = this._computationVector.length();
  48789. if (this.radius === 0) {
  48790. this.radius = 0.0001; // Just to avoid division by zero
  48791. }
  48792. // Alpha
  48793. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48794. if (this._computationVector.z < 0) {
  48795. this.alpha = 2 * Math.PI - this.alpha;
  48796. }
  48797. // Beta
  48798. this.beta = Math.acos(this._computationVector.y / this.radius);
  48799. this._checkLimits();
  48800. };
  48801. ArcRotateCamera.prototype.setPosition = function (position) {
  48802. if (this.position.equals(position)) {
  48803. return;
  48804. }
  48805. this.position.copyFrom(position);
  48806. this.rebuildAnglesAndRadius();
  48807. };
  48808. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48809. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48810. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48811. if (target.getBoundingInfo) {
  48812. if (toBoundingCenter) {
  48813. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48814. }
  48815. else {
  48816. this._targetBoundingCenter = null;
  48817. }
  48818. this._targetHost = target;
  48819. this._target = this._getTargetPosition();
  48820. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48821. }
  48822. else {
  48823. var newTarget = target;
  48824. var currentTarget = this._getTargetPosition();
  48825. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48826. return;
  48827. }
  48828. this._targetHost = null;
  48829. this._target = newTarget;
  48830. this._targetBoundingCenter = null;
  48831. this.onMeshTargetChangedObservable.notifyObservers(null);
  48832. }
  48833. this.rebuildAnglesAndRadius();
  48834. };
  48835. ArcRotateCamera.prototype._getViewMatrix = function () {
  48836. // Compute
  48837. var cosa = Math.cos(this.alpha);
  48838. var sina = Math.sin(this.alpha);
  48839. var cosb = Math.cos(this.beta);
  48840. var sinb = Math.sin(this.beta);
  48841. if (sinb === 0) {
  48842. sinb = 0.0001;
  48843. }
  48844. var target = this._getTargetPosition();
  48845. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48846. target.addToRef(this._computationVector, this._newPosition);
  48847. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48848. if (!this._collider) {
  48849. this._collider = new BABYLON.Collider();
  48850. }
  48851. this._collider._radius = this.collisionRadius;
  48852. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48853. this._collisionTriggered = true;
  48854. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48855. }
  48856. else {
  48857. this.position.copyFrom(this._newPosition);
  48858. var up = this.upVector;
  48859. if (this.allowUpsideDown && sinb < 0) {
  48860. up = up.clone();
  48861. up = up.negate();
  48862. }
  48863. this._computeViewMatrix(this.position, target, up);
  48864. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48865. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48866. }
  48867. this._currentTarget = target;
  48868. return this._viewMatrix;
  48869. };
  48870. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48871. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48872. meshes = meshes || this.getScene().meshes;
  48873. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48874. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48875. this.radius = distance * this.zoomOnFactor;
  48876. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48877. };
  48878. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48879. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48880. var meshesOrMinMaxVector;
  48881. var distance;
  48882. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48883. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48884. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48885. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48886. }
  48887. else { //minMaxVector and distance
  48888. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48889. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48890. distance = minMaxVectorAndDistance.distance;
  48891. }
  48892. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48893. if (!doNotUpdateMaxZ) {
  48894. this.maxZ = distance * 2;
  48895. }
  48896. };
  48897. /**
  48898. * @override
  48899. * Override Camera.createRigCamera
  48900. */
  48901. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48902. var alphaShift = 0;
  48903. switch (this.cameraRigMode) {
  48904. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48905. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48906. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48907. case BABYLON.Camera.RIG_MODE_VR:
  48908. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48909. break;
  48910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48911. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48912. break;
  48913. }
  48914. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48915. rigCam._cameraRigParams = {};
  48916. return rigCam;
  48917. };
  48918. /**
  48919. * @override
  48920. * Override Camera._updateRigCameras
  48921. */
  48922. ArcRotateCamera.prototype._updateRigCameras = function () {
  48923. var camLeft = this._rigCameras[0];
  48924. var camRight = this._rigCameras[1];
  48925. camLeft.beta = camRight.beta = this.beta;
  48926. camLeft.radius = camRight.radius = this.radius;
  48927. switch (this.cameraRigMode) {
  48928. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48929. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48930. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48931. case BABYLON.Camera.RIG_MODE_VR:
  48932. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48933. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48934. break;
  48935. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48936. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48937. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48938. break;
  48939. }
  48940. _super.prototype._updateRigCameras.call(this);
  48941. };
  48942. ArcRotateCamera.prototype.dispose = function () {
  48943. this.inputs.clear();
  48944. _super.prototype.dispose.call(this);
  48945. };
  48946. ArcRotateCamera.prototype.getClassName = function () {
  48947. return "ArcRotateCamera";
  48948. };
  48949. __decorate([
  48950. BABYLON.serialize()
  48951. ], ArcRotateCamera.prototype, "alpha", void 0);
  48952. __decorate([
  48953. BABYLON.serialize()
  48954. ], ArcRotateCamera.prototype, "beta", void 0);
  48955. __decorate([
  48956. BABYLON.serialize()
  48957. ], ArcRotateCamera.prototype, "radius", void 0);
  48958. __decorate([
  48959. BABYLON.serializeAsVector3("target")
  48960. ], ArcRotateCamera.prototype, "_target", void 0);
  48961. __decorate([
  48962. BABYLON.serialize()
  48963. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48964. __decorate([
  48965. BABYLON.serialize()
  48966. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48967. __decorate([
  48968. BABYLON.serialize()
  48969. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48970. __decorate([
  48971. BABYLON.serialize()
  48972. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48973. __decorate([
  48974. BABYLON.serialize()
  48975. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48976. __decorate([
  48977. BABYLON.serialize()
  48978. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48979. __decorate([
  48980. BABYLON.serialize()
  48981. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48982. __decorate([
  48983. BABYLON.serialize()
  48984. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48985. __decorate([
  48986. BABYLON.serialize()
  48987. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48988. __decorate([
  48989. BABYLON.serialize()
  48990. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48991. __decorate([
  48992. BABYLON.serialize()
  48993. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48994. __decorate([
  48995. BABYLON.serialize()
  48996. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48997. __decorate([
  48998. BABYLON.serialize()
  48999. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49000. __decorate([
  49001. BABYLON.serializeAsVector3()
  49002. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49003. __decorate([
  49004. BABYLON.serialize()
  49005. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49006. __decorate([
  49007. BABYLON.serialize()
  49008. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49009. __decorate([
  49010. BABYLON.serialize()
  49011. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49012. return ArcRotateCamera;
  49013. }(BABYLON.TargetCamera));
  49014. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49015. })(BABYLON || (BABYLON = {}));
  49016. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49017. var BABYLON;
  49018. (function (BABYLON) {
  49019. /**
  49020. * The HemisphericLight simulates the ambient environment light,
  49021. * so the passed direction is the light reflection direction, not the incoming direction.
  49022. */
  49023. var HemisphericLight = /** @class */ (function (_super) {
  49024. __extends(HemisphericLight, _super);
  49025. /**
  49026. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49027. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49028. * The HemisphericLight can't cast shadows.
  49029. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49030. * @param name The friendly name of the light
  49031. * @param direction The direction of the light reflection
  49032. * @param scene The scene the light belongs to
  49033. */
  49034. function HemisphericLight(name, direction, scene) {
  49035. var _this = _super.call(this, name, scene) || this;
  49036. /**
  49037. * The groundColor is the light in the opposite direction to the one specified during creation.
  49038. * 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.
  49039. */
  49040. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49041. _this.direction = direction || BABYLON.Vector3.Up();
  49042. return _this;
  49043. }
  49044. HemisphericLight.prototype._buildUniformLayout = function () {
  49045. this._uniformBuffer.addUniform("vLightData", 4);
  49046. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49047. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49048. this._uniformBuffer.addUniform("vLightGround", 3);
  49049. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49050. this._uniformBuffer.addUniform("depthValues", 2);
  49051. this._uniformBuffer.create();
  49052. };
  49053. /**
  49054. * Returns the string "HemisphericLight".
  49055. * @return The class name
  49056. */
  49057. HemisphericLight.prototype.getClassName = function () {
  49058. return "HemisphericLight";
  49059. };
  49060. /**
  49061. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49062. * Returns the updated direction.
  49063. * @param target The target the direction should point to
  49064. * @return The computed direction
  49065. */
  49066. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49067. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49068. return this.direction;
  49069. };
  49070. /**
  49071. * Returns the shadow generator associated to the light.
  49072. * @returns Always null for hemispheric lights because it does not support shadows.
  49073. */
  49074. HemisphericLight.prototype.getShadowGenerator = function () {
  49075. return null;
  49076. };
  49077. /**
  49078. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49079. * @param effect The effect to update
  49080. * @param lightIndex The index of the light in the effect to update
  49081. * @returns The hemispheric light
  49082. */
  49083. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49084. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49085. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49086. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49087. return this;
  49088. };
  49089. /**
  49090. * @hidden internal use only.
  49091. */
  49092. HemisphericLight.prototype._getWorldMatrix = function () {
  49093. if (!this._worldMatrix) {
  49094. this._worldMatrix = BABYLON.Matrix.Identity();
  49095. }
  49096. return this._worldMatrix;
  49097. };
  49098. /**
  49099. * Returns the integer 3.
  49100. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49101. */
  49102. HemisphericLight.prototype.getTypeID = function () {
  49103. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49104. };
  49105. __decorate([
  49106. BABYLON.serializeAsColor3()
  49107. ], HemisphericLight.prototype, "groundColor", void 0);
  49108. __decorate([
  49109. BABYLON.serializeAsVector3()
  49110. ], HemisphericLight.prototype, "direction", void 0);
  49111. return HemisphericLight;
  49112. }(BABYLON.Light));
  49113. BABYLON.HemisphericLight = HemisphericLight;
  49114. })(BABYLON || (BABYLON = {}));
  49115. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49116. var BABYLON;
  49117. (function (BABYLON) {
  49118. /**
  49119. * Base implementation IShadowLight
  49120. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49121. */
  49122. var ShadowLight = /** @class */ (function (_super) {
  49123. __extends(ShadowLight, _super);
  49124. function ShadowLight() {
  49125. var _this = _super !== null && _super.apply(this, arguments) || this;
  49126. _this._needProjectionMatrixCompute = true;
  49127. return _this;
  49128. }
  49129. ShadowLight.prototype._setPosition = function (value) {
  49130. this._position = value;
  49131. };
  49132. Object.defineProperty(ShadowLight.prototype, "position", {
  49133. /**
  49134. * Sets the position the shadow will be casted from. Also use as the light position for both
  49135. * point and spot lights.
  49136. */
  49137. get: function () {
  49138. return this._position;
  49139. },
  49140. /**
  49141. * Sets the position the shadow will be casted from. Also use as the light position for both
  49142. * point and spot lights.
  49143. */
  49144. set: function (value) {
  49145. this._setPosition(value);
  49146. },
  49147. enumerable: true,
  49148. configurable: true
  49149. });
  49150. ShadowLight.prototype._setDirection = function (value) {
  49151. this._direction = value;
  49152. };
  49153. Object.defineProperty(ShadowLight.prototype, "direction", {
  49154. /**
  49155. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49156. * Also use as the light direction on spot and directional lights.
  49157. */
  49158. get: function () {
  49159. return this._direction;
  49160. },
  49161. /**
  49162. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49163. * Also use as the light direction on spot and directional lights.
  49164. */
  49165. set: function (value) {
  49166. this._setDirection(value);
  49167. },
  49168. enumerable: true,
  49169. configurable: true
  49170. });
  49171. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49172. /**
  49173. * Gets the shadow projection clipping minimum z value.
  49174. */
  49175. get: function () {
  49176. return this._shadowMinZ;
  49177. },
  49178. /**
  49179. * Sets the shadow projection clipping minimum z value.
  49180. */
  49181. set: function (value) {
  49182. this._shadowMinZ = value;
  49183. this.forceProjectionMatrixCompute();
  49184. },
  49185. enumerable: true,
  49186. configurable: true
  49187. });
  49188. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49189. /**
  49190. * Sets the shadow projection clipping maximum z value.
  49191. */
  49192. get: function () {
  49193. return this._shadowMaxZ;
  49194. },
  49195. /**
  49196. * Gets the shadow projection clipping maximum z value.
  49197. */
  49198. set: function (value) {
  49199. this._shadowMaxZ = value;
  49200. this.forceProjectionMatrixCompute();
  49201. },
  49202. enumerable: true,
  49203. configurable: true
  49204. });
  49205. /**
  49206. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49207. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49208. */
  49209. ShadowLight.prototype.computeTransformedInformation = function () {
  49210. if (this.parent && this.parent.getWorldMatrix) {
  49211. if (!this.transformedPosition) {
  49212. this.transformedPosition = BABYLON.Vector3.Zero();
  49213. }
  49214. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49215. // In case the direction is present.
  49216. if (this.direction) {
  49217. if (!this.transformedDirection) {
  49218. this.transformedDirection = BABYLON.Vector3.Zero();
  49219. }
  49220. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49221. }
  49222. return true;
  49223. }
  49224. return false;
  49225. };
  49226. /**
  49227. * Return the depth scale used for the shadow map.
  49228. * @returns the depth scale.
  49229. */
  49230. ShadowLight.prototype.getDepthScale = function () {
  49231. return 50.0;
  49232. };
  49233. /**
  49234. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49235. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49236. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49237. */
  49238. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49239. return this.transformedDirection ? this.transformedDirection : this.direction;
  49240. };
  49241. /**
  49242. * Returns the ShadowLight absolute position in the World.
  49243. * @returns the position vector in world space
  49244. */
  49245. ShadowLight.prototype.getAbsolutePosition = function () {
  49246. return this.transformedPosition ? this.transformedPosition : this.position;
  49247. };
  49248. /**
  49249. * Sets the ShadowLight direction toward the passed target.
  49250. * @param target The point tot target in local space
  49251. * @returns the updated ShadowLight direction
  49252. */
  49253. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49254. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49255. return this.direction;
  49256. };
  49257. /**
  49258. * Returns the light rotation in euler definition.
  49259. * @returns the x y z rotation in local space.
  49260. */
  49261. ShadowLight.prototype.getRotation = function () {
  49262. this.direction.normalize();
  49263. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49264. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49265. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49266. };
  49267. /**
  49268. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49269. * @returns true if a cube texture needs to be use
  49270. */
  49271. ShadowLight.prototype.needCube = function () {
  49272. return false;
  49273. };
  49274. /**
  49275. * Detects if the projection matrix requires to be recomputed this frame.
  49276. * @returns true if it requires to be recomputed otherwise, false.
  49277. */
  49278. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49279. return this._needProjectionMatrixCompute;
  49280. };
  49281. /**
  49282. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49283. */
  49284. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49285. this._needProjectionMatrixCompute = true;
  49286. };
  49287. /**
  49288. * Get the world matrix of the sahdow lights.
  49289. * @hidden Internal Use Only
  49290. */
  49291. ShadowLight.prototype._getWorldMatrix = function () {
  49292. if (!this._worldMatrix) {
  49293. this._worldMatrix = BABYLON.Matrix.Identity();
  49294. }
  49295. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49296. return this._worldMatrix;
  49297. };
  49298. /**
  49299. * Gets the minZ used for shadow according to both the scene and the light.
  49300. * @param activeCamera The camera we are returning the min for
  49301. * @returns the depth min z
  49302. */
  49303. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49304. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49305. };
  49306. /**
  49307. * Gets the maxZ used for shadow according to both the scene and the light.
  49308. * @param activeCamera The camera we are returning the max for
  49309. * @returns the depth max z
  49310. */
  49311. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49312. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49313. };
  49314. /**
  49315. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49316. * @param matrix The materix to updated with the projection information
  49317. * @param viewMatrix The transform matrix of the light
  49318. * @param renderList The list of mesh to render in the map
  49319. * @returns The current light
  49320. */
  49321. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49322. if (this.customProjectionMatrixBuilder) {
  49323. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49324. }
  49325. else {
  49326. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49327. }
  49328. return this;
  49329. };
  49330. __decorate([
  49331. BABYLON.serializeAsVector3()
  49332. ], ShadowLight.prototype, "position", null);
  49333. __decorate([
  49334. BABYLON.serializeAsVector3()
  49335. ], ShadowLight.prototype, "direction", null);
  49336. __decorate([
  49337. BABYLON.serialize()
  49338. ], ShadowLight.prototype, "shadowMinZ", null);
  49339. __decorate([
  49340. BABYLON.serialize()
  49341. ], ShadowLight.prototype, "shadowMaxZ", null);
  49342. return ShadowLight;
  49343. }(BABYLON.Light));
  49344. BABYLON.ShadowLight = ShadowLight;
  49345. })(BABYLON || (BABYLON = {}));
  49346. //# sourceMappingURL=babylon.shadowLight.js.map
  49347. var BABYLON;
  49348. (function (BABYLON) {
  49349. /**
  49350. * A point light is a light defined by an unique point in world space.
  49351. * The light is emitted in every direction from this point.
  49352. * A good example of a point light is a standard light bulb.
  49353. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49354. */
  49355. var PointLight = /** @class */ (function (_super) {
  49356. __extends(PointLight, _super);
  49357. /**
  49358. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49359. * A PointLight emits the light in every direction.
  49360. * It can cast shadows.
  49361. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49362. * ```javascript
  49363. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49364. * ```
  49365. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49366. * @param name The light friendly name
  49367. * @param position The position of the point light in the scene
  49368. * @param scene The scene the lights belongs to
  49369. */
  49370. function PointLight(name, position, scene) {
  49371. var _this = _super.call(this, name, scene) || this;
  49372. _this._shadowAngle = Math.PI / 2;
  49373. _this.position = position;
  49374. return _this;
  49375. }
  49376. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49377. /**
  49378. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49379. * This specifies what angle the shadow will use to be created.
  49380. *
  49381. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49382. */
  49383. get: function () {
  49384. return this._shadowAngle;
  49385. },
  49386. /**
  49387. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49388. * This specifies what angle the shadow will use to be created.
  49389. *
  49390. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49391. */
  49392. set: function (value) {
  49393. this._shadowAngle = value;
  49394. this.forceProjectionMatrixCompute();
  49395. },
  49396. enumerable: true,
  49397. configurable: true
  49398. });
  49399. Object.defineProperty(PointLight.prototype, "direction", {
  49400. /**
  49401. * Gets the direction if it has been set.
  49402. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49403. */
  49404. get: function () {
  49405. return this._direction;
  49406. },
  49407. /**
  49408. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49409. */
  49410. set: function (value) {
  49411. var previousNeedCube = this.needCube();
  49412. this._direction = value;
  49413. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49414. this._shadowGenerator.recreateShadowMap();
  49415. }
  49416. },
  49417. enumerable: true,
  49418. configurable: true
  49419. });
  49420. /**
  49421. * Returns the string "PointLight"
  49422. * @returns the class name
  49423. */
  49424. PointLight.prototype.getClassName = function () {
  49425. return "PointLight";
  49426. };
  49427. /**
  49428. * Returns the integer 0.
  49429. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49430. */
  49431. PointLight.prototype.getTypeID = function () {
  49432. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49433. };
  49434. /**
  49435. * Specifies wether or not the shadowmap should be a cube texture.
  49436. * @returns true if the shadowmap needs to be a cube texture.
  49437. */
  49438. PointLight.prototype.needCube = function () {
  49439. return !this.direction;
  49440. };
  49441. /**
  49442. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49443. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49444. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49445. */
  49446. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49447. if (this.direction) {
  49448. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49449. }
  49450. else {
  49451. switch (faceIndex) {
  49452. case 0:
  49453. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49454. case 1:
  49455. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49456. case 2:
  49457. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49458. case 3:
  49459. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49460. case 4:
  49461. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49462. case 5:
  49463. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49464. }
  49465. }
  49466. return BABYLON.Vector3.Zero();
  49467. };
  49468. /**
  49469. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49470. * - fov = PI / 2
  49471. * - aspect ratio : 1.0
  49472. * - z-near and far equal to the active camera minZ and maxZ.
  49473. * Returns the PointLight.
  49474. */
  49475. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49476. var activeCamera = this.getScene().activeCamera;
  49477. if (!activeCamera) {
  49478. return;
  49479. }
  49480. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49481. };
  49482. PointLight.prototype._buildUniformLayout = function () {
  49483. this._uniformBuffer.addUniform("vLightData", 4);
  49484. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49485. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49486. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49487. this._uniformBuffer.addUniform("depthValues", 2);
  49488. this._uniformBuffer.create();
  49489. };
  49490. /**
  49491. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49492. * @param effect The effect to update
  49493. * @param lightIndex The index of the light in the effect to update
  49494. * @returns The point light
  49495. */
  49496. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49497. if (this.computeTransformedInformation()) {
  49498. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49499. return this;
  49500. }
  49501. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49502. return this;
  49503. };
  49504. __decorate([
  49505. BABYLON.serialize()
  49506. ], PointLight.prototype, "shadowAngle", null);
  49507. return PointLight;
  49508. }(BABYLON.ShadowLight));
  49509. BABYLON.PointLight = PointLight;
  49510. })(BABYLON || (BABYLON = {}));
  49511. //# sourceMappingURL=babylon.pointLight.js.map
  49512. var BABYLON;
  49513. (function (BABYLON) {
  49514. /**
  49515. * A directional light is defined by a direction (what a surprise!).
  49516. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49517. * 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.
  49518. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49519. */
  49520. var DirectionalLight = /** @class */ (function (_super) {
  49521. __extends(DirectionalLight, _super);
  49522. /**
  49523. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49524. * The directional light is emitted from everywhere in the given direction.
  49525. * It can cast shawdows.
  49526. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49527. * @param name The friendly name of the light
  49528. * @param direction The direction of the light
  49529. * @param scene The scene the light belongs to
  49530. */
  49531. function DirectionalLight(name, direction, scene) {
  49532. var _this = _super.call(this, name, scene) || this;
  49533. _this._shadowFrustumSize = 0;
  49534. _this._shadowOrthoScale = 0.1;
  49535. /**
  49536. * Automatically compute the projection matrix to best fit (including all the casters)
  49537. * on each frame.
  49538. */
  49539. _this.autoUpdateExtends = true;
  49540. // Cache
  49541. _this._orthoLeft = Number.MAX_VALUE;
  49542. _this._orthoRight = Number.MIN_VALUE;
  49543. _this._orthoTop = Number.MIN_VALUE;
  49544. _this._orthoBottom = Number.MAX_VALUE;
  49545. _this.position = direction.scale(-1.0);
  49546. _this.direction = direction;
  49547. return _this;
  49548. }
  49549. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49550. /**
  49551. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49552. */
  49553. get: function () {
  49554. return this._shadowFrustumSize;
  49555. },
  49556. /**
  49557. * Specifies a fix frustum size for the shadow generation.
  49558. */
  49559. set: function (value) {
  49560. this._shadowFrustumSize = value;
  49561. this.forceProjectionMatrixCompute();
  49562. },
  49563. enumerable: true,
  49564. configurable: true
  49565. });
  49566. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49567. /**
  49568. * Gets the shadow projection scale against the optimal computed one.
  49569. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49570. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49571. */
  49572. get: function () {
  49573. return this._shadowOrthoScale;
  49574. },
  49575. /**
  49576. * Sets the shadow projection scale against the optimal computed one.
  49577. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49578. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49579. */
  49580. set: function (value) {
  49581. this._shadowOrthoScale = value;
  49582. this.forceProjectionMatrixCompute();
  49583. },
  49584. enumerable: true,
  49585. configurable: true
  49586. });
  49587. /**
  49588. * Returns the string "DirectionalLight".
  49589. * @return The class name
  49590. */
  49591. DirectionalLight.prototype.getClassName = function () {
  49592. return "DirectionalLight";
  49593. };
  49594. /**
  49595. * Returns the integer 1.
  49596. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49597. */
  49598. DirectionalLight.prototype.getTypeID = function () {
  49599. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49600. };
  49601. /**
  49602. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49603. * Returns the DirectionalLight Shadow projection matrix.
  49604. */
  49605. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49606. if (this.shadowFrustumSize > 0) {
  49607. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49608. }
  49609. else {
  49610. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49611. }
  49612. };
  49613. /**
  49614. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49615. * Returns the DirectionalLight Shadow projection matrix.
  49616. */
  49617. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49618. var activeCamera = this.getScene().activeCamera;
  49619. if (!activeCamera) {
  49620. return;
  49621. }
  49622. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49623. };
  49624. /**
  49625. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49626. * Returns the DirectionalLight Shadow projection matrix.
  49627. */
  49628. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49629. var activeCamera = this.getScene().activeCamera;
  49630. if (!activeCamera) {
  49631. return;
  49632. }
  49633. // Check extends
  49634. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49635. var tempVector3 = BABYLON.Vector3.Zero();
  49636. this._orthoLeft = Number.MAX_VALUE;
  49637. this._orthoRight = Number.MIN_VALUE;
  49638. this._orthoTop = Number.MIN_VALUE;
  49639. this._orthoBottom = Number.MAX_VALUE;
  49640. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49641. var mesh = renderList[meshIndex];
  49642. if (!mesh) {
  49643. continue;
  49644. }
  49645. var boundingInfo = mesh.getBoundingInfo();
  49646. var boundingBox = boundingInfo.boundingBox;
  49647. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49648. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49649. if (tempVector3.x < this._orthoLeft)
  49650. this._orthoLeft = tempVector3.x;
  49651. if (tempVector3.y < this._orthoBottom)
  49652. this._orthoBottom = tempVector3.y;
  49653. if (tempVector3.x > this._orthoRight)
  49654. this._orthoRight = tempVector3.x;
  49655. if (tempVector3.y > this._orthoTop)
  49656. this._orthoTop = tempVector3.y;
  49657. }
  49658. }
  49659. }
  49660. var xOffset = this._orthoRight - this._orthoLeft;
  49661. var yOffset = this._orthoTop - this._orthoBottom;
  49662. 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);
  49663. };
  49664. DirectionalLight.prototype._buildUniformLayout = function () {
  49665. this._uniformBuffer.addUniform("vLightData", 4);
  49666. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49667. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49668. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49669. this._uniformBuffer.addUniform("depthValues", 2);
  49670. this._uniformBuffer.create();
  49671. };
  49672. /**
  49673. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49674. * @param effect The effect to update
  49675. * @param lightIndex The index of the light in the effect to update
  49676. * @returns The directional light
  49677. */
  49678. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49679. if (this.computeTransformedInformation()) {
  49680. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49681. return this;
  49682. }
  49683. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49684. return this;
  49685. };
  49686. /**
  49687. * Gets the minZ used for shadow according to both the scene and the light.
  49688. *
  49689. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49690. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49691. * @param activeCamera The camera we are returning the min for
  49692. * @returns the depth min z
  49693. */
  49694. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49695. return 1;
  49696. };
  49697. /**
  49698. * Gets the maxZ used for shadow according to both the scene and the light.
  49699. *
  49700. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49701. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49702. * @param activeCamera The camera we are returning the max for
  49703. * @returns the depth max z
  49704. */
  49705. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49706. return 1;
  49707. };
  49708. __decorate([
  49709. BABYLON.serialize()
  49710. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49711. __decorate([
  49712. BABYLON.serialize()
  49713. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49714. __decorate([
  49715. BABYLON.serialize()
  49716. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49717. return DirectionalLight;
  49718. }(BABYLON.ShadowLight));
  49719. BABYLON.DirectionalLight = DirectionalLight;
  49720. })(BABYLON || (BABYLON = {}));
  49721. //# sourceMappingURL=babylon.directionalLight.js.map
  49722. var BABYLON;
  49723. (function (BABYLON) {
  49724. /**
  49725. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49726. * These values define a cone of light starting from the position, emitting toward the direction.
  49727. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49728. * and the exponent defines the speed of the decay of the light with distance (reach).
  49729. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49730. */
  49731. var SpotLight = /** @class */ (function (_super) {
  49732. __extends(SpotLight, _super);
  49733. /**
  49734. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49735. * It can cast shadows.
  49736. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49737. * @param name The light friendly name
  49738. * @param position The position of the spot light in the scene
  49739. * @param direction The direction of the light in the scene
  49740. * @param angle The cone angle of the light in Radians
  49741. * @param exponent The light decay speed with the distance from the emission spot
  49742. * @param scene The scene the lights belongs to
  49743. */
  49744. function SpotLight(name, position, direction, angle, exponent, scene) {
  49745. var _this = _super.call(this, name, scene) || this;
  49746. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49747. _this._projectionTextureLightNear = 1e-6;
  49748. _this._projectionTextureLightFar = 1000.0;
  49749. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49750. _this._projectionTextureViewLightDirty = true;
  49751. _this._projectionTextureProjectionLightDirty = true;
  49752. _this._projectionTextureDirty = true;
  49753. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49754. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49755. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49756. _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);
  49757. _this.position = position;
  49758. _this.direction = direction;
  49759. _this.angle = angle;
  49760. _this.exponent = exponent;
  49761. return _this;
  49762. }
  49763. Object.defineProperty(SpotLight.prototype, "angle", {
  49764. /**
  49765. * Gets the cone angle of the spot light in Radians.
  49766. */
  49767. get: function () {
  49768. return this._angle;
  49769. },
  49770. /**
  49771. * Sets the cone angle of the spot light in Radians.
  49772. */
  49773. set: function (value) {
  49774. this._angle = value;
  49775. this._projectionTextureProjectionLightDirty = true;
  49776. this.forceProjectionMatrixCompute();
  49777. },
  49778. enumerable: true,
  49779. configurable: true
  49780. });
  49781. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49782. /**
  49783. * Allows scaling the angle of the light for shadow generation only.
  49784. */
  49785. get: function () {
  49786. return this._shadowAngleScale;
  49787. },
  49788. /**
  49789. * Allows scaling the angle of the light for shadow generation only.
  49790. */
  49791. set: function (value) {
  49792. this._shadowAngleScale = value;
  49793. this.forceProjectionMatrixCompute();
  49794. },
  49795. enumerable: true,
  49796. configurable: true
  49797. });
  49798. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49799. /**
  49800. * Allows reading the projecton texture
  49801. */
  49802. get: function () {
  49803. return this._projectionTextureMatrix;
  49804. },
  49805. enumerable: true,
  49806. configurable: true
  49807. });
  49808. ;
  49809. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49810. /**
  49811. * Gets the near clip of the Spotlight for texture projection.
  49812. */
  49813. get: function () {
  49814. return this._projectionTextureLightNear;
  49815. },
  49816. /**
  49817. * Sets the near clip of the Spotlight for texture projection.
  49818. */
  49819. set: function (value) {
  49820. this._projectionTextureLightNear = value;
  49821. this._projectionTextureProjectionLightDirty = true;
  49822. },
  49823. enumerable: true,
  49824. configurable: true
  49825. });
  49826. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49827. /**
  49828. * Gets the far clip of the Spotlight for texture projection.
  49829. */
  49830. get: function () {
  49831. return this._projectionTextureLightFar;
  49832. },
  49833. /**
  49834. * Sets the far clip of the Spotlight for texture projection.
  49835. */
  49836. set: function (value) {
  49837. this._projectionTextureLightFar = value;
  49838. this._projectionTextureProjectionLightDirty = true;
  49839. },
  49840. enumerable: true,
  49841. configurable: true
  49842. });
  49843. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49844. /**
  49845. * Gets the Up vector of the Spotlight for texture projection.
  49846. */
  49847. get: function () {
  49848. return this._projectionTextureUpDirection;
  49849. },
  49850. /**
  49851. * Sets the Up vector of the Spotlight for texture projection.
  49852. */
  49853. set: function (value) {
  49854. this._projectionTextureUpDirection = value;
  49855. this._projectionTextureProjectionLightDirty = true;
  49856. },
  49857. enumerable: true,
  49858. configurable: true
  49859. });
  49860. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49861. /**
  49862. * Gets the projection texture of the light.
  49863. */
  49864. get: function () {
  49865. return this._projectionTexture;
  49866. },
  49867. /**
  49868. * Sets the projection texture of the light.
  49869. */
  49870. set: function (value) {
  49871. this._projectionTexture = value;
  49872. this._projectionTextureDirty = true;
  49873. },
  49874. enumerable: true,
  49875. configurable: true
  49876. });
  49877. /**
  49878. * Returns the string "SpotLight".
  49879. * @returns the class name
  49880. */
  49881. SpotLight.prototype.getClassName = function () {
  49882. return "SpotLight";
  49883. };
  49884. /**
  49885. * Returns the integer 2.
  49886. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49887. */
  49888. SpotLight.prototype.getTypeID = function () {
  49889. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49890. };
  49891. /**
  49892. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49893. */
  49894. SpotLight.prototype._setDirection = function (value) {
  49895. _super.prototype._setDirection.call(this, value);
  49896. this._projectionTextureViewLightDirty = true;
  49897. };
  49898. /**
  49899. * Overrides the position setter to recompute the projection texture view light Matrix.
  49900. */
  49901. SpotLight.prototype._setPosition = function (value) {
  49902. _super.prototype._setPosition.call(this, value);
  49903. this._projectionTextureViewLightDirty = true;
  49904. };
  49905. /**
  49906. * 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.
  49907. * Returns the SpotLight.
  49908. */
  49909. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49910. var activeCamera = this.getScene().activeCamera;
  49911. if (!activeCamera) {
  49912. return;
  49913. }
  49914. this._shadowAngleScale = this._shadowAngleScale || 1;
  49915. var angle = this._shadowAngleScale * this._angle;
  49916. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49917. };
  49918. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49919. this._projectionTextureViewLightDirty = false;
  49920. this._projectionTextureDirty = true;
  49921. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49922. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49923. };
  49924. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49925. this._projectionTextureProjectionLightDirty = false;
  49926. this._projectionTextureDirty = true;
  49927. var light_far = this.projectionTextureLightFar;
  49928. var light_near = this.projectionTextureLightNear;
  49929. var P = light_far / (light_far - light_near);
  49930. var Q = -P * light_near;
  49931. var S = 1.0 / Math.tan(this._angle / 2.0);
  49932. var A = 1.0;
  49933. 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);
  49934. };
  49935. /**
  49936. * Main function for light texture projection matrix computing.
  49937. */
  49938. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49939. this._projectionTextureDirty = false;
  49940. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49941. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49942. };
  49943. SpotLight.prototype._buildUniformLayout = function () {
  49944. this._uniformBuffer.addUniform("vLightData", 4);
  49945. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49946. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49947. this._uniformBuffer.addUniform("vLightDirection", 3);
  49948. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49949. this._uniformBuffer.addUniform("depthValues", 2);
  49950. this._uniformBuffer.create();
  49951. };
  49952. /**
  49953. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49954. * @param effect The effect to update
  49955. * @param lightIndex The index of the light in the effect to update
  49956. * @returns The spot light
  49957. */
  49958. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49959. var normalizeDirection;
  49960. if (this.computeTransformedInformation()) {
  49961. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49962. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49963. }
  49964. else {
  49965. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49966. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49967. }
  49968. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49969. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49970. if (this._projectionTextureViewLightDirty) {
  49971. this._computeProjectionTextureViewLightMatrix();
  49972. }
  49973. if (this._projectionTextureProjectionLightDirty) {
  49974. this._computeProjectionTextureProjectionLightMatrix();
  49975. }
  49976. if (this._projectionTextureDirty) {
  49977. this._computeProjectionTextureMatrix();
  49978. }
  49979. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49980. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49981. }
  49982. return this;
  49983. };
  49984. /**
  49985. * Disposes the light and the associated resources.
  49986. */
  49987. SpotLight.prototype.dispose = function () {
  49988. _super.prototype.dispose.call(this);
  49989. if (this._projectionTexture) {
  49990. this._projectionTexture.dispose();
  49991. }
  49992. };
  49993. __decorate([
  49994. BABYLON.serialize()
  49995. ], SpotLight.prototype, "angle", null);
  49996. __decorate([
  49997. BABYLON.serialize()
  49998. ], SpotLight.prototype, "shadowAngleScale", null);
  49999. __decorate([
  50000. BABYLON.serialize()
  50001. ], SpotLight.prototype, "exponent", void 0);
  50002. __decorate([
  50003. BABYLON.serialize()
  50004. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50005. __decorate([
  50006. BABYLON.serialize()
  50007. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50008. __decorate([
  50009. BABYLON.serialize()
  50010. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50011. __decorate([
  50012. BABYLON.serializeAsTexture("projectedLightTexture")
  50013. ], SpotLight.prototype, "_projectionTexture", void 0);
  50014. return SpotLight;
  50015. }(BABYLON.ShadowLight));
  50016. BABYLON.SpotLight = SpotLight;
  50017. })(BABYLON || (BABYLON = {}));
  50018. //# sourceMappingURL=babylon.spotLight.js.map
  50019. var BABYLON;
  50020. (function (BABYLON) {
  50021. /**
  50022. * Class used to override all child animations of a given target
  50023. */
  50024. var AnimationPropertiesOverride = /** @class */ (function () {
  50025. function AnimationPropertiesOverride() {
  50026. /**
  50027. * Gets or sets a value indicating if animation blending must be used
  50028. */
  50029. this.enableBlending = false;
  50030. /**
  50031. * Gets or sets the blending speed to use when enableBlending is true
  50032. */
  50033. this.blendingSpeed = 0.01;
  50034. /**
  50035. * Gets or sets the default loop mode to use
  50036. */
  50037. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50038. }
  50039. return AnimationPropertiesOverride;
  50040. }());
  50041. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50042. })(BABYLON || (BABYLON = {}));
  50043. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50044. var BABYLON;
  50045. (function (BABYLON) {
  50046. /**
  50047. * Represents the range of an animation
  50048. */
  50049. var AnimationRange = /** @class */ (function () {
  50050. /**
  50051. * Initializes the range of an animation
  50052. * @param name The name of the animation range
  50053. * @param from The starting frame of the animation
  50054. * @param to The ending frame of the animation
  50055. */
  50056. function AnimationRange(
  50057. /**The name of the animation range**/
  50058. name,
  50059. /**The starting frame of the animation */
  50060. from,
  50061. /**The ending frame of the animation*/
  50062. to) {
  50063. this.name = name;
  50064. this.from = from;
  50065. this.to = to;
  50066. }
  50067. /**
  50068. * Makes a copy of the animation range
  50069. * @returns A copy of the animation range
  50070. */
  50071. AnimationRange.prototype.clone = function () {
  50072. return new AnimationRange(this.name, this.from, this.to);
  50073. };
  50074. return AnimationRange;
  50075. }());
  50076. BABYLON.AnimationRange = AnimationRange;
  50077. /**
  50078. * Composed of a frame, and an action function
  50079. */
  50080. var AnimationEvent = /** @class */ (function () {
  50081. /**
  50082. * Initializes the animation event
  50083. * @param frame The frame for which the event is triggered
  50084. * @param action The event to perform when triggered
  50085. * @param onlyOnce Specifies if the event should be triggered only once
  50086. */
  50087. function AnimationEvent(
  50088. /** The frame for which the event is triggered **/
  50089. frame,
  50090. /** The event to perform when triggered **/
  50091. action,
  50092. /** Specifies if the event should be triggered only once**/
  50093. onlyOnce) {
  50094. this.frame = frame;
  50095. this.action = action;
  50096. this.onlyOnce = onlyOnce;
  50097. /**
  50098. * Specifies if the animation event is done
  50099. */
  50100. this.isDone = false;
  50101. }
  50102. return AnimationEvent;
  50103. }());
  50104. BABYLON.AnimationEvent = AnimationEvent;
  50105. /**
  50106. * A cursor which tracks a point on a path
  50107. */
  50108. var PathCursor = /** @class */ (function () {
  50109. /**
  50110. * Initializes the path cursor
  50111. * @param path The path to track
  50112. */
  50113. function PathCursor(path) {
  50114. this.path = path;
  50115. /**
  50116. * Stores path cursor callbacks for when an onchange event is triggered
  50117. */
  50118. this._onchange = new Array();
  50119. /**
  50120. * The value of the path cursor
  50121. */
  50122. this.value = 0;
  50123. /**
  50124. * The animation array of the path cursor
  50125. */
  50126. this.animations = new Array();
  50127. }
  50128. /**
  50129. * Gets the cursor point on the path
  50130. * @returns A point on the path cursor at the cursor location
  50131. */
  50132. PathCursor.prototype.getPoint = function () {
  50133. var point = this.path.getPointAtLengthPosition(this.value);
  50134. return new BABYLON.Vector3(point.x, 0, point.y);
  50135. };
  50136. /**
  50137. * Moves the cursor ahead by the step amount
  50138. * @param step The amount to move the cursor forward
  50139. * @returns This path cursor
  50140. */
  50141. PathCursor.prototype.moveAhead = function (step) {
  50142. if (step === void 0) { step = 0.002; }
  50143. this.move(step);
  50144. return this;
  50145. };
  50146. /**
  50147. * Moves the cursor behind by the step amount
  50148. * @param step The amount to move the cursor back
  50149. * @returns This path cursor
  50150. */
  50151. PathCursor.prototype.moveBack = function (step) {
  50152. if (step === void 0) { step = 0.002; }
  50153. this.move(-step);
  50154. return this;
  50155. };
  50156. /**
  50157. * Moves the cursor by the step amount
  50158. * If the step amount is greater than one, an exception is thrown
  50159. * @param step The amount to move the cursor
  50160. * @returns This path cursor
  50161. */
  50162. PathCursor.prototype.move = function (step) {
  50163. if (Math.abs(step) > 1) {
  50164. throw "step size should be less than 1.";
  50165. }
  50166. this.value += step;
  50167. this.ensureLimits();
  50168. this.raiseOnChange();
  50169. return this;
  50170. };
  50171. /**
  50172. * Ensures that the value is limited between zero and one
  50173. * @returns This path cursor
  50174. */
  50175. PathCursor.prototype.ensureLimits = function () {
  50176. while (this.value > 1) {
  50177. this.value -= 1;
  50178. }
  50179. while (this.value < 0) {
  50180. this.value += 1;
  50181. }
  50182. return this;
  50183. };
  50184. /**
  50185. * Runs onchange callbacks on change (used by the animation engine)
  50186. * @returns This path cursor
  50187. */
  50188. PathCursor.prototype.raiseOnChange = function () {
  50189. var _this = this;
  50190. this._onchange.forEach(function (f) { return f(_this); });
  50191. return this;
  50192. };
  50193. /**
  50194. * Executes a function on change
  50195. * @param f A path cursor onchange callback
  50196. * @returns This path cursor
  50197. */
  50198. PathCursor.prototype.onchange = function (f) {
  50199. this._onchange.push(f);
  50200. return this;
  50201. };
  50202. return PathCursor;
  50203. }());
  50204. BABYLON.PathCursor = PathCursor;
  50205. /**
  50206. * Enum for the animation key frame interpolation type
  50207. */
  50208. var AnimationKeyInterpolation;
  50209. (function (AnimationKeyInterpolation) {
  50210. /**
  50211. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50212. */
  50213. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50214. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50215. /**
  50216. * Class used to store any kind of animation
  50217. */
  50218. var Animation = /** @class */ (function () {
  50219. /**
  50220. * Initializes the animation
  50221. * @param name Name of the animation
  50222. * @param targetProperty Property to animate
  50223. * @param framePerSecond The frames per second of the animation
  50224. * @param dataType The data type of the animation
  50225. * @param loopMode The loop mode of the animation
  50226. * @param enableBlendings Specifies if blending should be enabled
  50227. */
  50228. function Animation(
  50229. /**Name of the animation */
  50230. name,
  50231. /**Property to animate */
  50232. targetProperty,
  50233. /**The frames per second of the animation */
  50234. framePerSecond,
  50235. /**The data type of the animation */
  50236. dataType,
  50237. /**The loop mode of the animation */
  50238. loopMode,
  50239. /**Specifies if blending should be enabled */
  50240. enableBlending) {
  50241. this.name = name;
  50242. this.targetProperty = targetProperty;
  50243. this.framePerSecond = framePerSecond;
  50244. this.dataType = dataType;
  50245. this.loopMode = loopMode;
  50246. this.enableBlending = enableBlending;
  50247. /**
  50248. * @hidden Internal use only
  50249. */
  50250. this._runtimeAnimations = new Array();
  50251. /**
  50252. * The set of event that will be linked to this animation
  50253. */
  50254. this._events = new Array();
  50255. /**
  50256. * Stores the blending speed of the animation
  50257. */
  50258. this.blendingSpeed = 0.01;
  50259. /**
  50260. * Stores the animation ranges for the animation
  50261. */
  50262. this._ranges = {};
  50263. this.targetPropertyPath = targetProperty.split(".");
  50264. this.dataType = dataType;
  50265. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50266. }
  50267. /**
  50268. * @hidden Internal use
  50269. */
  50270. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50271. var dataType = undefined;
  50272. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50273. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50274. }
  50275. else if (from instanceof BABYLON.Quaternion) {
  50276. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50277. }
  50278. else if (from instanceof BABYLON.Vector3) {
  50279. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50280. }
  50281. else if (from instanceof BABYLON.Vector2) {
  50282. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50283. }
  50284. else if (from instanceof BABYLON.Color3) {
  50285. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50286. }
  50287. else if (from instanceof BABYLON.Size) {
  50288. dataType = Animation.ANIMATIONTYPE_SIZE;
  50289. }
  50290. if (dataType == undefined) {
  50291. return null;
  50292. }
  50293. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50294. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50295. animation.setKeys(keys);
  50296. if (easingFunction !== undefined) {
  50297. animation.setEasingFunction(easingFunction);
  50298. }
  50299. return animation;
  50300. };
  50301. /**
  50302. * Sets up an animation
  50303. * @param property The property to animate
  50304. * @param animationType The animation type to apply
  50305. * @param framePerSecond The frames per second of the animation
  50306. * @param easingFunction The easing function used in the animation
  50307. * @returns The created animation
  50308. */
  50309. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50310. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50311. animation.setEasingFunction(easingFunction);
  50312. return animation;
  50313. };
  50314. /**
  50315. * Create and start an animation on a node
  50316. * @param name defines the name of the global animation that will be run on all nodes
  50317. * @param node defines the root node where the animation will take place
  50318. * @param targetProperty defines property to animate
  50319. * @param framePerSecond defines the number of frame per second yo use
  50320. * @param totalFrame defines the number of frames in total
  50321. * @param from defines the initial value
  50322. * @param to defines the final value
  50323. * @param loopMode defines which loop mode you want to use (off by default)
  50324. * @param easingFunction defines the easing function to use (linear by default)
  50325. * @param onAnimationEnd defines the callback to call when animation end
  50326. * @returns the animatable created for this animation
  50327. */
  50328. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50329. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50330. if (!animation) {
  50331. return null;
  50332. }
  50333. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50334. };
  50335. /**
  50336. * Create and start an animation on a node and its descendants
  50337. * @param name defines the name of the global animation that will be run on all nodes
  50338. * @param node defines the root node where the animation will take place
  50339. * @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
  50340. * @param targetProperty defines property to animate
  50341. * @param framePerSecond defines the number of frame per second to use
  50342. * @param totalFrame defines the number of frames in total
  50343. * @param from defines the initial value
  50344. * @param to defines the final value
  50345. * @param loopMode defines which loop mode you want to use (off by default)
  50346. * @param easingFunction defines the easing function to use (linear by default)
  50347. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50348. * @returns the list of animatables created for all nodes
  50349. * @example https://www.babylonjs-playground.com/#MH0VLI
  50350. */
  50351. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50352. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50353. if (!animation) {
  50354. return null;
  50355. }
  50356. var scene = node.getScene();
  50357. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50358. };
  50359. /**
  50360. * Creates a new animation, merges it with the existing animations and starts it
  50361. * @param name Name of the animation
  50362. * @param node Node which contains the scene that begins the animations
  50363. * @param targetProperty Specifies which property to animate
  50364. * @param framePerSecond The frames per second of the animation
  50365. * @param totalFrame The total number of frames
  50366. * @param from The frame at the beginning of the animation
  50367. * @param to The frame at the end of the animation
  50368. * @param loopMode Specifies the loop mode of the animation
  50369. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50370. * @param onAnimationEnd Callback to run once the animation is complete
  50371. * @returns Nullable animation
  50372. */
  50373. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50374. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50375. if (!animation) {
  50376. return null;
  50377. }
  50378. node.animations.push(animation);
  50379. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50380. };
  50381. /**
  50382. * Transition property of the Camera to the target Value
  50383. * @param property The property to transition
  50384. * @param targetValue The target Value of the property
  50385. * @param host The object where the property to animate belongs
  50386. * @param scene Scene used to run the animation
  50387. * @param frameRate Framerate (in frame/s) to use
  50388. * @param transition The transition type we want to use
  50389. * @param duration The duration of the animation, in milliseconds
  50390. * @param onAnimationEnd Callback trigger at the end of the animation
  50391. * @returns Nullable animation
  50392. */
  50393. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50394. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50395. if (duration <= 0) {
  50396. host[property] = targetValue;
  50397. if (onAnimationEnd) {
  50398. onAnimationEnd();
  50399. }
  50400. return null;
  50401. }
  50402. var endFrame = frameRate * (duration / 1000);
  50403. transition.setKeys([{
  50404. frame: 0,
  50405. value: host[property].clone ? host[property].clone() : host[property]
  50406. },
  50407. {
  50408. frame: endFrame,
  50409. value: targetValue
  50410. }]);
  50411. if (!host.animations) {
  50412. host.animations = [];
  50413. }
  50414. host.animations.push(transition);
  50415. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50416. animation.onAnimationEnd = onAnimationEnd;
  50417. return animation;
  50418. };
  50419. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50420. /**
  50421. * Return the array of runtime animations currently using this animation
  50422. */
  50423. get: function () {
  50424. return this._runtimeAnimations;
  50425. },
  50426. enumerable: true,
  50427. configurable: true
  50428. });
  50429. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50430. /**
  50431. * Specifies if any of the runtime animations are currently running
  50432. */
  50433. get: function () {
  50434. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50435. var runtimeAnimation = _a[_i];
  50436. if (!runtimeAnimation.isStopped) {
  50437. return true;
  50438. }
  50439. }
  50440. return false;
  50441. },
  50442. enumerable: true,
  50443. configurable: true
  50444. });
  50445. // Methods
  50446. /**
  50447. * Converts the animation to a string
  50448. * @param fullDetails support for multiple levels of logging within scene loading
  50449. * @returns String form of the animation
  50450. */
  50451. Animation.prototype.toString = function (fullDetails) {
  50452. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50453. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50454. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50455. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50456. if (fullDetails) {
  50457. ret += ", Ranges: {";
  50458. var first = true;
  50459. for (var name in this._ranges) {
  50460. if (first) {
  50461. ret += ", ";
  50462. first = false;
  50463. }
  50464. ret += name;
  50465. }
  50466. ret += "}";
  50467. }
  50468. return ret;
  50469. };
  50470. /**
  50471. * Add an event to this animation
  50472. * @param event Event to add
  50473. */
  50474. Animation.prototype.addEvent = function (event) {
  50475. this._events.push(event);
  50476. };
  50477. /**
  50478. * Remove all events found at the given frame
  50479. * @param frame The frame to remove events from
  50480. */
  50481. Animation.prototype.removeEvents = function (frame) {
  50482. for (var index = 0; index < this._events.length; index++) {
  50483. if (this._events[index].frame === frame) {
  50484. this._events.splice(index, 1);
  50485. index--;
  50486. }
  50487. }
  50488. };
  50489. /**
  50490. * Retrieves all the events from the animation
  50491. * @returns Events from the animation
  50492. */
  50493. Animation.prototype.getEvents = function () {
  50494. return this._events;
  50495. };
  50496. /**
  50497. * Creates an animation range
  50498. * @param name Name of the animation range
  50499. * @param from Starting frame of the animation range
  50500. * @param to Ending frame of the animation
  50501. */
  50502. Animation.prototype.createRange = function (name, from, to) {
  50503. // check name not already in use; could happen for bones after serialized
  50504. if (!this._ranges[name]) {
  50505. this._ranges[name] = new AnimationRange(name, from, to);
  50506. }
  50507. };
  50508. /**
  50509. * Deletes an animation range by name
  50510. * @param name Name of the animation range to delete
  50511. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50512. */
  50513. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50514. if (deleteFrames === void 0) { deleteFrames = true; }
  50515. var range = this._ranges[name];
  50516. if (!range) {
  50517. return;
  50518. }
  50519. if (deleteFrames) {
  50520. var from = range.from;
  50521. var to = range.to;
  50522. // this loop MUST go high to low for multiple splices to work
  50523. for (var key = this._keys.length - 1; key >= 0; key--) {
  50524. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50525. this._keys.splice(key, 1);
  50526. }
  50527. }
  50528. }
  50529. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50530. };
  50531. /**
  50532. * Gets the animation range by name, or null if not defined
  50533. * @param name Name of the animation range
  50534. * @returns Nullable animation range
  50535. */
  50536. Animation.prototype.getRange = function (name) {
  50537. return this._ranges[name];
  50538. };
  50539. /**
  50540. * Gets the key frames from the animation
  50541. * @returns The key frames of the animation
  50542. */
  50543. Animation.prototype.getKeys = function () {
  50544. return this._keys;
  50545. };
  50546. /**
  50547. * Gets the highest frame rate of the animation
  50548. * @returns Highest frame rate of the animation
  50549. */
  50550. Animation.prototype.getHighestFrame = function () {
  50551. var ret = 0;
  50552. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50553. if (ret < this._keys[key].frame) {
  50554. ret = this._keys[key].frame;
  50555. }
  50556. }
  50557. return ret;
  50558. };
  50559. /**
  50560. * Gets the easing function of the animation
  50561. * @returns Easing function of the animation
  50562. */
  50563. Animation.prototype.getEasingFunction = function () {
  50564. return this._easingFunction;
  50565. };
  50566. /**
  50567. * Sets the easing function of the animation
  50568. * @param easingFunction A custom mathematical formula for animation
  50569. */
  50570. Animation.prototype.setEasingFunction = function (easingFunction) {
  50571. this._easingFunction = easingFunction;
  50572. };
  50573. /**
  50574. * Interpolates a scalar linearly
  50575. * @param startValue Start value of the animation curve
  50576. * @param endValue End value of the animation curve
  50577. * @param gradient Scalar amount to interpolate
  50578. * @returns Interpolated scalar value
  50579. */
  50580. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50581. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50582. };
  50583. /**
  50584. * Interpolates a scalar cubically
  50585. * @param startValue Start value of the animation curve
  50586. * @param outTangent End tangent of the animation
  50587. * @param endValue End value of the animation curve
  50588. * @param inTangent Start tangent of the animation curve
  50589. * @param gradient Scalar amount to interpolate
  50590. * @returns Interpolated scalar value
  50591. */
  50592. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50593. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50594. };
  50595. /**
  50596. * Interpolates a quaternion using a spherical linear interpolation
  50597. * @param startValue Start value of the animation curve
  50598. * @param endValue End value of the animation curve
  50599. * @param gradient Scalar amount to interpolate
  50600. * @returns Interpolated quaternion value
  50601. */
  50602. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50603. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50604. };
  50605. /**
  50606. * Interpolates a quaternion cubically
  50607. * @param startValue Start value of the animation curve
  50608. * @param outTangent End tangent of the animation curve
  50609. * @param endValue End value of the animation curve
  50610. * @param inTangent Start tangent of the animation curve
  50611. * @param gradient Scalar amount to interpolate
  50612. * @returns Interpolated quaternion value
  50613. */
  50614. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50615. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50616. };
  50617. /**
  50618. * Interpolates a Vector3 linearl
  50619. * @param startValue Start value of the animation curve
  50620. * @param endValue End value of the animation curve
  50621. * @param gradient Scalar amount to interpolate
  50622. * @returns Interpolated scalar value
  50623. */
  50624. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50625. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50626. };
  50627. /**
  50628. * Interpolates a Vector3 cubically
  50629. * @param startValue Start value of the animation curve
  50630. * @param outTangent End tangent of the animation
  50631. * @param endValue End value of the animation curve
  50632. * @param inTangent Start tangent of the animation curve
  50633. * @param gradient Scalar amount to interpolate
  50634. * @returns InterpolatedVector3 value
  50635. */
  50636. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50637. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50638. };
  50639. /**
  50640. * Interpolates a Vector2 linearly
  50641. * @param startValue Start value of the animation curve
  50642. * @param endValue End value of the animation curve
  50643. * @param gradient Scalar amount to interpolate
  50644. * @returns Interpolated Vector2 value
  50645. */
  50646. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50647. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50648. };
  50649. /**
  50650. * Interpolates a Vector2 cubically
  50651. * @param startValue Start value of the animation curve
  50652. * @param outTangent End tangent of the animation
  50653. * @param endValue End value of the animation curve
  50654. * @param inTangent Start tangent of the animation curve
  50655. * @param gradient Scalar amount to interpolate
  50656. * @returns Interpolated Vector2 value
  50657. */
  50658. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50659. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50660. };
  50661. /**
  50662. * Interpolates a size linearly
  50663. * @param startValue Start value of the animation curve
  50664. * @param endValue End value of the animation curve
  50665. * @param gradient Scalar amount to interpolate
  50666. * @returns Interpolated Size value
  50667. */
  50668. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50669. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50670. };
  50671. /**
  50672. * Interpolates a Color3 linearly
  50673. * @param startValue Start value of the animation curve
  50674. * @param endValue End value of the animation curve
  50675. * @param gradient Scalar amount to interpolate
  50676. * @returns Interpolated Color3 value
  50677. */
  50678. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50679. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50680. };
  50681. /**
  50682. * @hidden Internal use only
  50683. */
  50684. Animation.prototype._getKeyValue = function (value) {
  50685. if (typeof value === "function") {
  50686. return value();
  50687. }
  50688. return value;
  50689. };
  50690. /**
  50691. * @hidden Internal use only
  50692. */
  50693. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50694. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50695. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50696. }
  50697. var keys = this.getKeys();
  50698. // Try to get a hash to find the right key
  50699. 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));
  50700. if (keys[startKeyIndex].frame >= currentFrame) {
  50701. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50702. startKeyIndex--;
  50703. }
  50704. }
  50705. for (var key = startKeyIndex; key < keys.length; key++) {
  50706. var endKey = keys[key + 1];
  50707. if (endKey.frame >= currentFrame) {
  50708. var startKey = keys[key];
  50709. var startValue = this._getKeyValue(startKey.value);
  50710. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50711. return startValue;
  50712. }
  50713. var endValue = this._getKeyValue(endKey.value);
  50714. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50715. var frameDelta = endKey.frame - startKey.frame;
  50716. // gradient : percent of currentFrame between the frame inf and the frame sup
  50717. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50718. // check for easingFunction and correction of gradient
  50719. var easingFunction = this.getEasingFunction();
  50720. if (easingFunction != null) {
  50721. gradient = easingFunction.ease(gradient);
  50722. }
  50723. switch (this.dataType) {
  50724. // Float
  50725. case Animation.ANIMATIONTYPE_FLOAT:
  50726. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50727. switch (loopMode) {
  50728. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50729. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50730. return floatValue;
  50731. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50732. return offsetValue * repeatCount + floatValue;
  50733. }
  50734. break;
  50735. // Quaternion
  50736. case Animation.ANIMATIONTYPE_QUATERNION:
  50737. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50738. switch (loopMode) {
  50739. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50740. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50741. return quatValue;
  50742. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50743. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50744. }
  50745. return quatValue;
  50746. // Vector3
  50747. case Animation.ANIMATIONTYPE_VECTOR3:
  50748. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50749. switch (loopMode) {
  50750. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50751. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50752. return vec3Value;
  50753. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50754. return vec3Value.add(offsetValue.scale(repeatCount));
  50755. }
  50756. // Vector2
  50757. case Animation.ANIMATIONTYPE_VECTOR2:
  50758. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50759. switch (loopMode) {
  50760. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50761. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50762. return vec2Value;
  50763. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50764. return vec2Value.add(offsetValue.scale(repeatCount));
  50765. }
  50766. // Size
  50767. case Animation.ANIMATIONTYPE_SIZE:
  50768. switch (loopMode) {
  50769. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50770. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50771. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50772. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50773. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50774. }
  50775. // Color3
  50776. case Animation.ANIMATIONTYPE_COLOR3:
  50777. switch (loopMode) {
  50778. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50779. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50780. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50781. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50782. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50783. }
  50784. // Matrix
  50785. case Animation.ANIMATIONTYPE_MATRIX:
  50786. switch (loopMode) {
  50787. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50788. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50789. if (Animation.AllowMatricesInterpolation) {
  50790. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50791. }
  50792. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50793. return startValue;
  50794. }
  50795. default:
  50796. break;
  50797. }
  50798. break;
  50799. }
  50800. }
  50801. return this._getKeyValue(keys[keys.length - 1].value);
  50802. };
  50803. /**
  50804. * Defines the function to use to interpolate matrices
  50805. * @param startValue defines the start matrix
  50806. * @param endValue defines the end matrix
  50807. * @param gradient defines the gradient between both matrices
  50808. * @param result defines an optional target matrix where to store the interpolation
  50809. * @returns the interpolated matrix
  50810. */
  50811. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50812. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50813. if (result) {
  50814. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50815. return result;
  50816. }
  50817. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50818. }
  50819. if (result) {
  50820. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50821. return result;
  50822. }
  50823. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50824. };
  50825. /**
  50826. * Makes a copy of the animation
  50827. * @returns Cloned animation
  50828. */
  50829. Animation.prototype.clone = function () {
  50830. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50831. clone.enableBlending = this.enableBlending;
  50832. clone.blendingSpeed = this.blendingSpeed;
  50833. if (this._keys) {
  50834. clone.setKeys(this._keys);
  50835. }
  50836. if (this._ranges) {
  50837. clone._ranges = {};
  50838. for (var name in this._ranges) {
  50839. var range = this._ranges[name];
  50840. if (!range) {
  50841. continue;
  50842. }
  50843. clone._ranges[name] = range.clone();
  50844. }
  50845. }
  50846. return clone;
  50847. };
  50848. /**
  50849. * Sets the key frames of the animation
  50850. * @param values The animation key frames to set
  50851. */
  50852. Animation.prototype.setKeys = function (values) {
  50853. this._keys = values.slice(0);
  50854. };
  50855. /**
  50856. * Serializes the animation to an object
  50857. * @returns Serialized object
  50858. */
  50859. Animation.prototype.serialize = function () {
  50860. var serializationObject = {};
  50861. serializationObject.name = this.name;
  50862. serializationObject.property = this.targetProperty;
  50863. serializationObject.framePerSecond = this.framePerSecond;
  50864. serializationObject.dataType = this.dataType;
  50865. serializationObject.loopBehavior = this.loopMode;
  50866. serializationObject.enableBlending = this.enableBlending;
  50867. serializationObject.blendingSpeed = this.blendingSpeed;
  50868. var dataType = this.dataType;
  50869. serializationObject.keys = [];
  50870. var keys = this.getKeys();
  50871. for (var index = 0; index < keys.length; index++) {
  50872. var animationKey = keys[index];
  50873. var key = {};
  50874. key.frame = animationKey.frame;
  50875. switch (dataType) {
  50876. case Animation.ANIMATIONTYPE_FLOAT:
  50877. key.values = [animationKey.value];
  50878. break;
  50879. case Animation.ANIMATIONTYPE_QUATERNION:
  50880. case Animation.ANIMATIONTYPE_MATRIX:
  50881. case Animation.ANIMATIONTYPE_VECTOR3:
  50882. case Animation.ANIMATIONTYPE_COLOR3:
  50883. key.values = animationKey.value.asArray();
  50884. break;
  50885. }
  50886. serializationObject.keys.push(key);
  50887. }
  50888. serializationObject.ranges = [];
  50889. for (var name in this._ranges) {
  50890. var source = this._ranges[name];
  50891. if (!source) {
  50892. continue;
  50893. }
  50894. var range = {};
  50895. range.name = name;
  50896. range.from = source.from;
  50897. range.to = source.to;
  50898. serializationObject.ranges.push(range);
  50899. }
  50900. return serializationObject;
  50901. };
  50902. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50903. /**
  50904. * Get the float animation type
  50905. */
  50906. get: function () {
  50907. return Animation._ANIMATIONTYPE_FLOAT;
  50908. },
  50909. enumerable: true,
  50910. configurable: true
  50911. });
  50912. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50913. /**
  50914. * Get the Vector3 animation type
  50915. */
  50916. get: function () {
  50917. return Animation._ANIMATIONTYPE_VECTOR3;
  50918. },
  50919. enumerable: true,
  50920. configurable: true
  50921. });
  50922. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50923. /**
  50924. * Get the Vectpr2 animation type
  50925. */
  50926. get: function () {
  50927. return Animation._ANIMATIONTYPE_VECTOR2;
  50928. },
  50929. enumerable: true,
  50930. configurable: true
  50931. });
  50932. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50933. /**
  50934. * Get the Size animation type
  50935. */
  50936. get: function () {
  50937. return Animation._ANIMATIONTYPE_SIZE;
  50938. },
  50939. enumerable: true,
  50940. configurable: true
  50941. });
  50942. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50943. /**
  50944. * Get the Quaternion animation type
  50945. */
  50946. get: function () {
  50947. return Animation._ANIMATIONTYPE_QUATERNION;
  50948. },
  50949. enumerable: true,
  50950. configurable: true
  50951. });
  50952. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50953. /**
  50954. * Get the Matrix animation type
  50955. */
  50956. get: function () {
  50957. return Animation._ANIMATIONTYPE_MATRIX;
  50958. },
  50959. enumerable: true,
  50960. configurable: true
  50961. });
  50962. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50963. /**
  50964. * Get the Color3 animation type
  50965. */
  50966. get: function () {
  50967. return Animation._ANIMATIONTYPE_COLOR3;
  50968. },
  50969. enumerable: true,
  50970. configurable: true
  50971. });
  50972. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50973. /**
  50974. * Get the Relative Loop Mode
  50975. */
  50976. get: function () {
  50977. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50978. },
  50979. enumerable: true,
  50980. configurable: true
  50981. });
  50982. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50983. /**
  50984. * Get the Cycle Loop Mode
  50985. */
  50986. get: function () {
  50987. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50988. },
  50989. enumerable: true,
  50990. configurable: true
  50991. });
  50992. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50993. /**
  50994. * Get the Constant Loop Mode
  50995. */
  50996. get: function () {
  50997. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50998. },
  50999. enumerable: true,
  51000. configurable: true
  51001. });
  51002. /**
  51003. * Parses an animation object and creates an animation
  51004. * @param parsedAnimation Parsed animation object
  51005. * @returns Animation object
  51006. */
  51007. Animation.Parse = function (parsedAnimation) {
  51008. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51009. var dataType = parsedAnimation.dataType;
  51010. var keys = [];
  51011. var data;
  51012. var index;
  51013. if (parsedAnimation.enableBlending) {
  51014. animation.enableBlending = parsedAnimation.enableBlending;
  51015. }
  51016. if (parsedAnimation.blendingSpeed) {
  51017. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51018. }
  51019. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51020. var key = parsedAnimation.keys[index];
  51021. var inTangent;
  51022. var outTangent;
  51023. switch (dataType) {
  51024. case Animation.ANIMATIONTYPE_FLOAT:
  51025. data = key.values[0];
  51026. if (key.values.length >= 1) {
  51027. inTangent = key.values[1];
  51028. }
  51029. if (key.values.length >= 2) {
  51030. outTangent = key.values[2];
  51031. }
  51032. break;
  51033. case Animation.ANIMATIONTYPE_QUATERNION:
  51034. data = BABYLON.Quaternion.FromArray(key.values);
  51035. if (key.values.length >= 8) {
  51036. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51037. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51038. inTangent = _inTangent;
  51039. }
  51040. }
  51041. if (key.values.length >= 12) {
  51042. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51043. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51044. outTangent = _outTangent;
  51045. }
  51046. }
  51047. break;
  51048. case Animation.ANIMATIONTYPE_MATRIX:
  51049. data = BABYLON.Matrix.FromArray(key.values);
  51050. break;
  51051. case Animation.ANIMATIONTYPE_COLOR3:
  51052. data = BABYLON.Color3.FromArray(key.values);
  51053. break;
  51054. case Animation.ANIMATIONTYPE_VECTOR3:
  51055. default:
  51056. data = BABYLON.Vector3.FromArray(key.values);
  51057. break;
  51058. }
  51059. var keyData = {};
  51060. keyData.frame = key.frame;
  51061. keyData.value = data;
  51062. if (inTangent != undefined) {
  51063. keyData.inTangent = inTangent;
  51064. }
  51065. if (outTangent != undefined) {
  51066. keyData.outTangent = outTangent;
  51067. }
  51068. keys.push(keyData);
  51069. }
  51070. animation.setKeys(keys);
  51071. if (parsedAnimation.ranges) {
  51072. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51073. data = parsedAnimation.ranges[index];
  51074. animation.createRange(data.name, data.from, data.to);
  51075. }
  51076. }
  51077. return animation;
  51078. };
  51079. /**
  51080. * Appends the serialized animations from the source animations
  51081. * @param source Source containing the animations
  51082. * @param destination Target to store the animations
  51083. */
  51084. Animation.AppendSerializedAnimations = function (source, destination) {
  51085. if (source.animations) {
  51086. destination.animations = [];
  51087. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51088. var animation = source.animations[animationIndex];
  51089. destination.animations.push(animation.serialize());
  51090. }
  51091. }
  51092. };
  51093. /**
  51094. * Use matrix interpolation instead of using direct key value when animating matrices
  51095. */
  51096. Animation.AllowMatricesInterpolation = false;
  51097. /**
  51098. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51099. */
  51100. Animation.AllowMatrixDecomposeForInterpolation = true;
  51101. // Statics
  51102. /**
  51103. * Float animation type
  51104. */
  51105. Animation._ANIMATIONTYPE_FLOAT = 0;
  51106. /**
  51107. * Vector3 animation type
  51108. */
  51109. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51110. /**
  51111. * Quaternion animation type
  51112. */
  51113. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51114. /**
  51115. * Matrix animation type
  51116. */
  51117. Animation._ANIMATIONTYPE_MATRIX = 3;
  51118. /**
  51119. * Color3 animation type
  51120. */
  51121. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51122. /**
  51123. * Vector2 animation type
  51124. */
  51125. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51126. /**
  51127. * Size animation type
  51128. */
  51129. Animation._ANIMATIONTYPE_SIZE = 6;
  51130. /**
  51131. * Relative Loop Mode
  51132. */
  51133. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51134. /**
  51135. * Cycle Loop Mode
  51136. */
  51137. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51138. /**
  51139. * Constant Loop Mode
  51140. */
  51141. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51142. return Animation;
  51143. }());
  51144. BABYLON.Animation = Animation;
  51145. })(BABYLON || (BABYLON = {}));
  51146. //# sourceMappingURL=babylon.animation.js.map
  51147. var BABYLON;
  51148. (function (BABYLON) {
  51149. /**
  51150. * This class defines the direct association between an animation and a target
  51151. */
  51152. var TargetedAnimation = /** @class */ (function () {
  51153. function TargetedAnimation() {
  51154. }
  51155. return TargetedAnimation;
  51156. }());
  51157. BABYLON.TargetedAnimation = TargetedAnimation;
  51158. /**
  51159. * Use this class to create coordinated animations on multiple targets
  51160. */
  51161. var AnimationGroup = /** @class */ (function () {
  51162. function AnimationGroup(name, scene) {
  51163. if (scene === void 0) { scene = null; }
  51164. this.name = name;
  51165. this._targetedAnimations = new Array();
  51166. this._animatables = new Array();
  51167. this._from = Number.MAX_VALUE;
  51168. this._to = -Number.MAX_VALUE;
  51169. this._speedRatio = 1;
  51170. this.onAnimationEndObservable = new BABYLON.Observable();
  51171. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51172. this._scene.animationGroups.push(this);
  51173. }
  51174. Object.defineProperty(AnimationGroup.prototype, "from", {
  51175. /**
  51176. * Gets the first frame
  51177. */
  51178. get: function () {
  51179. return this._from;
  51180. },
  51181. enumerable: true,
  51182. configurable: true
  51183. });
  51184. Object.defineProperty(AnimationGroup.prototype, "to", {
  51185. /**
  51186. * Gets the last frame
  51187. */
  51188. get: function () {
  51189. return this._to;
  51190. },
  51191. enumerable: true,
  51192. configurable: true
  51193. });
  51194. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51195. /**
  51196. * Define if the animations are started
  51197. */
  51198. get: function () {
  51199. return this._isStarted;
  51200. },
  51201. enumerable: true,
  51202. configurable: true
  51203. });
  51204. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51205. /**
  51206. * Gets or sets the speed ratio to use for all animations
  51207. */
  51208. get: function () {
  51209. return this._speedRatio;
  51210. },
  51211. /**
  51212. * Gets or sets the speed ratio to use for all animations
  51213. */
  51214. set: function (value) {
  51215. if (this._speedRatio === value) {
  51216. return;
  51217. }
  51218. this._speedRatio = value;
  51219. for (var index = 0; index < this._animatables.length; index++) {
  51220. var animatable = this._animatables[index];
  51221. animatable.speedRatio = this._speedRatio;
  51222. }
  51223. },
  51224. enumerable: true,
  51225. configurable: true
  51226. });
  51227. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51228. /**
  51229. * Gets the targeted animations for this animation group
  51230. */
  51231. get: function () {
  51232. return this._targetedAnimations;
  51233. },
  51234. enumerable: true,
  51235. configurable: true
  51236. });
  51237. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51238. /**
  51239. * returning the list of animatables controlled by this animation group.
  51240. */
  51241. get: function () {
  51242. return this._animatables;
  51243. },
  51244. enumerable: true,
  51245. configurable: true
  51246. });
  51247. /**
  51248. * Add an animation (with its target) in the group
  51249. * @param animation defines the animation we want to add
  51250. * @param target defines the target of the animation
  51251. * @returns the {BABYLON.TargetedAnimation} object
  51252. */
  51253. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51254. var targetedAnimation = {
  51255. animation: animation,
  51256. target: target
  51257. };
  51258. var keys = animation.getKeys();
  51259. if (this._from > keys[0].frame) {
  51260. this._from = keys[0].frame;
  51261. }
  51262. if (this._to < keys[keys.length - 1].frame) {
  51263. this._to = keys[keys.length - 1].frame;
  51264. }
  51265. this._targetedAnimations.push(targetedAnimation);
  51266. return targetedAnimation;
  51267. };
  51268. /**
  51269. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51270. * It can add constant keys at begin or end
  51271. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  51272. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  51273. */
  51274. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51275. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  51276. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  51277. beginFrame = Math.max(beginFrame, this._from);
  51278. endFrame = Math.min(endFrame, this._to);
  51279. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51280. var targetedAnimation = this._targetedAnimations[index];
  51281. var keys = targetedAnimation.animation.getKeys();
  51282. var startKey = keys[0];
  51283. var endKey = keys[keys.length - 1];
  51284. if (startKey.frame > beginFrame) {
  51285. var newKey = {
  51286. frame: beginFrame,
  51287. value: startKey.value,
  51288. inTangent: startKey.inTangent,
  51289. outTangent: startKey.outTangent,
  51290. interpolation: startKey.interpolation
  51291. };
  51292. keys.splice(0, 0, newKey);
  51293. }
  51294. if (endKey.frame < endFrame) {
  51295. var newKey = {
  51296. frame: endFrame,
  51297. value: endKey.value,
  51298. inTangent: endKey.outTangent,
  51299. outTangent: endKey.outTangent,
  51300. interpolation: endKey.interpolation
  51301. };
  51302. keys.push(newKey);
  51303. }
  51304. }
  51305. return this;
  51306. };
  51307. /**
  51308. * Start all animations on given targets
  51309. * @param loop defines if animations must loop
  51310. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51311. * @param from defines the from key (optional)
  51312. * @param to defines the to key (optional)
  51313. * @returns the current animation group
  51314. */
  51315. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51316. var _this = this;
  51317. if (loop === void 0) { loop = false; }
  51318. if (speedRatio === void 0) { speedRatio = 1; }
  51319. if (this._isStarted || this._targetedAnimations.length === 0) {
  51320. return this;
  51321. }
  51322. var _loop_1 = function (targetedAnimation) {
  51323. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51324. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51325. }));
  51326. };
  51327. var this_1 = this;
  51328. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51329. var targetedAnimation = _a[_i];
  51330. _loop_1(targetedAnimation);
  51331. }
  51332. this._speedRatio = speedRatio;
  51333. this._isStarted = true;
  51334. return this;
  51335. };
  51336. /**
  51337. * Pause all animations
  51338. */
  51339. AnimationGroup.prototype.pause = function () {
  51340. if (!this._isStarted) {
  51341. return this;
  51342. }
  51343. for (var index = 0; index < this._animatables.length; index++) {
  51344. var animatable = this._animatables[index];
  51345. animatable.pause();
  51346. }
  51347. return this;
  51348. };
  51349. /**
  51350. * Play all animations to initial state
  51351. * This function will start() the animations if they were not started or will restart() them if they were paused
  51352. * @param loop defines if animations must loop
  51353. */
  51354. AnimationGroup.prototype.play = function (loop) {
  51355. if (this.isStarted) {
  51356. if (loop !== undefined) {
  51357. for (var index = 0; index < this._animatables.length; index++) {
  51358. var animatable = this._animatables[index];
  51359. animatable.loopAnimation = loop;
  51360. }
  51361. }
  51362. this.restart();
  51363. }
  51364. else {
  51365. this.start(loop, this._speedRatio);
  51366. }
  51367. return this;
  51368. };
  51369. /**
  51370. * Reset all animations to initial state
  51371. */
  51372. AnimationGroup.prototype.reset = function () {
  51373. if (!this._isStarted) {
  51374. return this;
  51375. }
  51376. for (var index = 0; index < this._animatables.length; index++) {
  51377. var animatable = this._animatables[index];
  51378. animatable.reset();
  51379. }
  51380. return this;
  51381. };
  51382. /**
  51383. * Restart animations from key 0
  51384. */
  51385. AnimationGroup.prototype.restart = function () {
  51386. if (!this._isStarted) {
  51387. return this;
  51388. }
  51389. for (var index = 0; index < this._animatables.length; index++) {
  51390. var animatable = this._animatables[index];
  51391. animatable.restart();
  51392. }
  51393. return this;
  51394. };
  51395. /**
  51396. * Stop all animations
  51397. */
  51398. AnimationGroup.prototype.stop = function () {
  51399. if (!this._isStarted) {
  51400. return this;
  51401. }
  51402. for (var index = 0; index < this._animatables.length; index++) {
  51403. var animatable = this._animatables[index];
  51404. animatable.stop();
  51405. }
  51406. this._isStarted = false;
  51407. return this;
  51408. };
  51409. /**
  51410. * Set animation weight for all animatables
  51411. * @param weight defines the weight to use
  51412. * @return the animationGroup
  51413. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51414. */
  51415. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51416. for (var index = 0; index < this._animatables.length; index++) {
  51417. var animatable = this._animatables[index];
  51418. animatable.weight = weight;
  51419. }
  51420. return this;
  51421. };
  51422. /**
  51423. * Synchronize and normalize all animatables with a source animatable
  51424. * @param root defines the root animatable to synchronize with
  51425. * @return the animationGroup
  51426. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51427. */
  51428. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51429. for (var index = 0; index < this._animatables.length; index++) {
  51430. var animatable = this._animatables[index];
  51431. animatable.syncWith(root);
  51432. }
  51433. return this;
  51434. };
  51435. /**
  51436. * Goes to a specific frame in this animation group
  51437. * @param frame the frame number to go to
  51438. * @return the animationGroup
  51439. */
  51440. AnimationGroup.prototype.goToFrame = function (frame) {
  51441. if (!this._isStarted) {
  51442. return this;
  51443. }
  51444. for (var index = 0; index < this._animatables.length; index++) {
  51445. var animatable = this._animatables[index];
  51446. animatable.goToFrame(frame);
  51447. }
  51448. return this;
  51449. };
  51450. /**
  51451. * Dispose all associated resources
  51452. */
  51453. AnimationGroup.prototype.dispose = function () {
  51454. this._targetedAnimations = [];
  51455. this._animatables = [];
  51456. var index = this._scene.animationGroups.indexOf(this);
  51457. if (index > -1) {
  51458. this._scene.animationGroups.splice(index, 1);
  51459. }
  51460. };
  51461. return AnimationGroup;
  51462. }());
  51463. BABYLON.AnimationGroup = AnimationGroup;
  51464. })(BABYLON || (BABYLON = {}));
  51465. //# sourceMappingURL=babylon.animationGroup.js.map
  51466. var BABYLON;
  51467. (function (BABYLON) {
  51468. /**
  51469. * Defines a runtime animation
  51470. */
  51471. var RuntimeAnimation = /** @class */ (function () {
  51472. /**
  51473. * Create a new RuntimeAnimation object
  51474. * @param target defines the target of the animation
  51475. * @param animation defines the source animation object
  51476. * @param scene defines the hosting scene
  51477. * @param host defines the initiating Animatable
  51478. */
  51479. function RuntimeAnimation(target, animation, scene, host) {
  51480. /**
  51481. * The current frame of the runtime animation
  51482. */
  51483. this._currentFrame = 0;
  51484. /**
  51485. * The offsets cache of the runtime animation
  51486. */
  51487. this._offsetsCache = {};
  51488. /**
  51489. * The high limits cache of the runtime animation
  51490. */
  51491. this._highLimitsCache = {};
  51492. /**
  51493. * Specifies if the runtime animation has been stopped
  51494. */
  51495. this._stopped = false;
  51496. /**
  51497. * The blending factor of the runtime animation
  51498. */
  51499. this._blendingFactor = 0;
  51500. /**
  51501. * The target path of the runtime animation
  51502. */
  51503. this._targetPath = "";
  51504. /**
  51505. * The weight of the runtime animation
  51506. */
  51507. this._weight = 1.0;
  51508. /**
  51509. * The ratio offset of the runtime animation
  51510. */
  51511. this._ratioOffset = 0;
  51512. /**
  51513. * The previous delay of the runtime animation
  51514. */
  51515. this._previousDelay = 0;
  51516. /**
  51517. * The previous ratio of the runtime animation
  51518. */
  51519. this._previousRatio = 0;
  51520. this._animation = animation;
  51521. this._target = target;
  51522. this._scene = scene;
  51523. this._host = host;
  51524. animation._runtimeAnimations.push(this);
  51525. }
  51526. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51527. /**
  51528. * Gets the current frame of the runtime animation
  51529. */
  51530. get: function () {
  51531. return this._currentFrame;
  51532. },
  51533. enumerable: true,
  51534. configurable: true
  51535. });
  51536. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51537. /**
  51538. * Gets the weight of the runtime animation
  51539. */
  51540. get: function () {
  51541. return this._weight;
  51542. },
  51543. enumerable: true,
  51544. configurable: true
  51545. });
  51546. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51547. /**
  51548. * Gets the original value of the runtime animation
  51549. */
  51550. get: function () {
  51551. return this._originalValue;
  51552. },
  51553. enumerable: true,
  51554. configurable: true
  51555. });
  51556. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51557. /**
  51558. * Gets the current value of the runtime animation
  51559. */
  51560. get: function () {
  51561. return this._currentValue;
  51562. },
  51563. enumerable: true,
  51564. configurable: true
  51565. });
  51566. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51567. /**
  51568. * Gets the target path of the runtime animation
  51569. */
  51570. get: function () {
  51571. return this._targetPath;
  51572. },
  51573. enumerable: true,
  51574. configurable: true
  51575. });
  51576. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51577. /**
  51578. * Gets the actual target of the runtime animation
  51579. */
  51580. get: function () {
  51581. return this._activeTarget;
  51582. },
  51583. enumerable: true,
  51584. configurable: true
  51585. });
  51586. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51587. /**
  51588. * Gets the animation from the runtime animation
  51589. */
  51590. get: function () {
  51591. return this._animation;
  51592. },
  51593. enumerable: true,
  51594. configurable: true
  51595. });
  51596. /**
  51597. * Resets the runtime animation to the beginning
  51598. */
  51599. RuntimeAnimation.prototype.reset = function () {
  51600. this._offsetsCache = {};
  51601. this._highLimitsCache = {};
  51602. this._currentFrame = 0;
  51603. this._blendingFactor = 0;
  51604. this._originalValue = null;
  51605. };
  51606. /**
  51607. * Specifies if the runtime animation is stopped
  51608. * @returns Boolean specifying if the runtime animation is stopped
  51609. */
  51610. RuntimeAnimation.prototype.isStopped = function () {
  51611. return this._stopped;
  51612. };
  51613. /**
  51614. * Disposes of the runtime animation
  51615. */
  51616. RuntimeAnimation.prototype.dispose = function () {
  51617. var index = this._animation.runtimeAnimations.indexOf(this);
  51618. if (index > -1) {
  51619. this._animation.runtimeAnimations.splice(index, 1);
  51620. }
  51621. };
  51622. /**
  51623. * Interpolates the animation from the current frame
  51624. * @param currentFrame The frame to interpolate the animation to
  51625. * @param repeatCount The number of times that the animation should loop
  51626. * @param loopMode The type of looping mode to use
  51627. * @param offsetValue Animation offset value
  51628. * @param highLimitValue The high limit value
  51629. * @returns The interpolated value
  51630. */
  51631. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51632. this._currentFrame = currentFrame;
  51633. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51634. this._workValue = BABYLON.Matrix.Zero();
  51635. }
  51636. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51637. };
  51638. /**
  51639. * Affect the interpolated value to the target
  51640. * @param currentValue defines the value computed by the animation
  51641. * @param weight defines the weight to apply to this value
  51642. */
  51643. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51644. if (weight === void 0) { weight = 1.0; }
  51645. if (this._target instanceof Array) {
  51646. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51647. var target = _a[_i];
  51648. this._setValue(target, currentValue, weight);
  51649. }
  51650. }
  51651. else {
  51652. this._setValue(this._target, currentValue, weight);
  51653. }
  51654. };
  51655. /**
  51656. * Sets the value of the runtime animation
  51657. * @param target The target property of the runtime animation
  51658. * @param currentValue The current value to use for the runtime animation
  51659. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51660. */
  51661. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51662. if (weight === void 0) { weight = 1.0; }
  51663. // Set value
  51664. var path;
  51665. var destination;
  51666. var targetPropertyPath = this._animation.targetPropertyPath;
  51667. if (targetPropertyPath.length > 1) {
  51668. var property = target[targetPropertyPath[0]];
  51669. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51670. property = property[targetPropertyPath[index]];
  51671. }
  51672. path = targetPropertyPath[targetPropertyPath.length - 1];
  51673. destination = property;
  51674. }
  51675. else {
  51676. path = targetPropertyPath[0];
  51677. destination = target;
  51678. }
  51679. this._targetPath = path;
  51680. this._activeTarget = destination;
  51681. this._weight = weight;
  51682. // Blending
  51683. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51684. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51685. if (enableBlending && this._blendingFactor <= 1.0) {
  51686. if (!this._originalBlendValue) {
  51687. var originalValue = destination[path];
  51688. if (originalValue.clone) {
  51689. this._originalBlendValue = originalValue.clone();
  51690. }
  51691. else {
  51692. this._originalBlendValue = originalValue;
  51693. }
  51694. }
  51695. }
  51696. if (weight !== -1.0) {
  51697. if (!this._originalValue) {
  51698. var originalValue = void 0;
  51699. if (destination.getRestPose && path === "_matrix") { // For bones
  51700. originalValue = destination.getRestPose();
  51701. }
  51702. else {
  51703. originalValue = destination[path];
  51704. }
  51705. if (originalValue.clone) {
  51706. this._originalValue = originalValue.clone();
  51707. }
  51708. else {
  51709. this._originalValue = originalValue;
  51710. }
  51711. }
  51712. }
  51713. if (enableBlending && this._blendingFactor <= 1.0) {
  51714. if (this._originalBlendValue.m) { // Matrix
  51715. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51716. if (this._currentValue) {
  51717. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51718. }
  51719. else {
  51720. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51721. }
  51722. }
  51723. else {
  51724. if (this._currentValue) {
  51725. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51726. }
  51727. else {
  51728. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51729. }
  51730. }
  51731. }
  51732. else {
  51733. var constructor = this._originalBlendValue.constructor;
  51734. if (constructor.Lerp) { // Lerp supported
  51735. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51736. }
  51737. else if (constructor.Slerp) { // Slerp supported
  51738. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51739. }
  51740. else if (this._originalBlendValue.toFixed) { // Number
  51741. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51742. }
  51743. else { // Blending not supported
  51744. this._currentValue = currentValue;
  51745. }
  51746. }
  51747. this._blendingFactor += blendingSpeed;
  51748. }
  51749. else {
  51750. this._currentValue = currentValue;
  51751. }
  51752. if (weight !== -1.0) {
  51753. this._scene._registerTargetForLateAnimationBinding(this);
  51754. }
  51755. else {
  51756. destination[path] = this._currentValue;
  51757. }
  51758. if (target.markAsDirty) {
  51759. target.markAsDirty(this._animation.targetProperty);
  51760. }
  51761. };
  51762. /**
  51763. * Gets the loop pmode of the runtime animation
  51764. * @returns Loop Mode
  51765. */
  51766. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51767. if (this._target && this._target.animationPropertiesOverride) {
  51768. return this._target.animationPropertiesOverride.loopMode;
  51769. }
  51770. return this._animation.loopMode;
  51771. };
  51772. /**
  51773. * Move the current animation to a given frame
  51774. * @param frame defines the frame to move to
  51775. */
  51776. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51777. var keys = this._animation.getKeys();
  51778. if (frame < keys[0].frame) {
  51779. frame = keys[0].frame;
  51780. }
  51781. else if (frame > keys[keys.length - 1].frame) {
  51782. frame = keys[keys.length - 1].frame;
  51783. }
  51784. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51785. this.setValue(currentValue, -1);
  51786. };
  51787. /**
  51788. * @hidden Internal use only
  51789. */
  51790. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51791. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51792. this._ratioOffset = this._previousRatio - newRatio;
  51793. };
  51794. /**
  51795. * Execute the current animation
  51796. * @param delay defines the delay to add to the current frame
  51797. * @param from defines the lower bound of the animation range
  51798. * @param to defines the upper bound of the animation range
  51799. * @param loop defines if the current animation must loop
  51800. * @param speedRatio defines the current speed ratio
  51801. * @param weight defines the weight of the animation (default is -1 so no weight)
  51802. * @returns a boolean indicating if the animation has ended
  51803. */
  51804. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51805. if (weight === void 0) { weight = -1.0; }
  51806. var targetPropertyPath = this._animation.targetPropertyPath;
  51807. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51808. this._stopped = true;
  51809. return false;
  51810. }
  51811. var returnValue = true;
  51812. var keys = this._animation.getKeys();
  51813. // Adding a start key at frame 0 if missing
  51814. if (keys[0].frame !== 0) {
  51815. var newKey = { frame: 0, value: keys[0].value };
  51816. keys.splice(0, 0, newKey);
  51817. }
  51818. // Check limits
  51819. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51820. from = keys[0].frame;
  51821. }
  51822. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51823. to = keys[keys.length - 1].frame;
  51824. }
  51825. //to and from cannot be the same key
  51826. if (from === to) {
  51827. if (from > keys[0].frame) {
  51828. from--;
  51829. }
  51830. else if (to < keys[keys.length - 1].frame) {
  51831. to++;
  51832. }
  51833. }
  51834. // Compute ratio
  51835. var range = to - from;
  51836. var offsetValue;
  51837. // ratio represents the frame delta between from and to
  51838. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51839. var highLimitValue = 0;
  51840. this._previousDelay = delay;
  51841. this._previousRatio = ratio;
  51842. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51843. returnValue = false;
  51844. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51845. }
  51846. else {
  51847. // Get max value if required
  51848. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51849. var keyOffset = to.toString() + from.toString();
  51850. if (!this._offsetsCache[keyOffset]) {
  51851. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51852. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51853. switch (this._animation.dataType) {
  51854. // Float
  51855. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51856. this._offsetsCache[keyOffset] = toValue - fromValue;
  51857. break;
  51858. // Quaternion
  51859. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51860. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51861. break;
  51862. // Vector3
  51863. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51864. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51865. // Vector2
  51866. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51867. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51868. // Size
  51869. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51870. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51871. // Color3
  51872. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51873. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51874. default:
  51875. break;
  51876. }
  51877. this._highLimitsCache[keyOffset] = toValue;
  51878. }
  51879. highLimitValue = this._highLimitsCache[keyOffset];
  51880. offsetValue = this._offsetsCache[keyOffset];
  51881. }
  51882. }
  51883. if (offsetValue === undefined) {
  51884. switch (this._animation.dataType) {
  51885. // Float
  51886. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51887. offsetValue = 0;
  51888. break;
  51889. // Quaternion
  51890. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51891. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51892. break;
  51893. // Vector3
  51894. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51895. offsetValue = BABYLON.Vector3.Zero();
  51896. break;
  51897. // Vector2
  51898. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51899. offsetValue = BABYLON.Vector2.Zero();
  51900. break;
  51901. // Size
  51902. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51903. offsetValue = BABYLON.Size.Zero();
  51904. break;
  51905. // Color3
  51906. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51907. offsetValue = BABYLON.Color3.Black();
  51908. }
  51909. }
  51910. // Compute value
  51911. var repeatCount = (ratio / range) >> 0;
  51912. var currentFrame = returnValue ? from + ratio % range : to;
  51913. // Need to normalize?
  51914. if (this._host && this._host.syncRoot) {
  51915. var syncRoot = this._host.syncRoot;
  51916. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51917. currentFrame = from + (to - from) * hostNormalizedFrame;
  51918. }
  51919. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51920. // Set value
  51921. this.setValue(currentValue, weight);
  51922. // Check events
  51923. var events = this._animation.getEvents();
  51924. for (var index = 0; index < events.length; index++) {
  51925. // Make sure current frame has passed event frame and that event frame is within the current range
  51926. // Also, handle both forward and reverse animations
  51927. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51928. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51929. var event = events[index];
  51930. if (!event.isDone) {
  51931. // If event should be done only once, remove it.
  51932. if (event.onlyOnce) {
  51933. events.splice(index, 1);
  51934. index--;
  51935. }
  51936. event.isDone = true;
  51937. event.action();
  51938. } // Don't do anything if the event has already be done.
  51939. }
  51940. else if (events[index].isDone && !events[index].onlyOnce) {
  51941. // reset event, the animation is looping
  51942. events[index].isDone = false;
  51943. }
  51944. }
  51945. if (!returnValue) {
  51946. this._stopped = true;
  51947. }
  51948. return returnValue;
  51949. };
  51950. return RuntimeAnimation;
  51951. }());
  51952. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51953. })(BABYLON || (BABYLON = {}));
  51954. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51955. var BABYLON;
  51956. (function (BABYLON) {
  51957. var Animatable = /** @class */ (function () {
  51958. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51959. if (fromFrame === void 0) { fromFrame = 0; }
  51960. if (toFrame === void 0) { toFrame = 100; }
  51961. if (loopAnimation === void 0) { loopAnimation = false; }
  51962. if (speedRatio === void 0) { speedRatio = 1.0; }
  51963. this.target = target;
  51964. this.fromFrame = fromFrame;
  51965. this.toFrame = toFrame;
  51966. this.loopAnimation = loopAnimation;
  51967. this.onAnimationEnd = onAnimationEnd;
  51968. this._localDelayOffset = null;
  51969. this._pausedDelay = null;
  51970. this._runtimeAnimations = new Array();
  51971. this._paused = false;
  51972. this._speedRatio = 1;
  51973. this._weight = -1.0;
  51974. this.animationStarted = false;
  51975. this._scene = scene;
  51976. if (animations) {
  51977. this.appendAnimations(target, animations);
  51978. }
  51979. this._speedRatio = speedRatio;
  51980. scene._activeAnimatables.push(this);
  51981. }
  51982. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51983. /**
  51984. * Gets the root Animatable used to synchronize and normalize animations
  51985. */
  51986. get: function () {
  51987. return this._syncRoot;
  51988. },
  51989. enumerable: true,
  51990. configurable: true
  51991. });
  51992. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51993. /**
  51994. * Gets the current frame of the first RuntimeAnimation
  51995. * Used to synchronize Animatables
  51996. */
  51997. get: function () {
  51998. if (this._runtimeAnimations.length === 0) {
  51999. return 0;
  52000. }
  52001. return this._runtimeAnimations[0].currentFrame;
  52002. },
  52003. enumerable: true,
  52004. configurable: true
  52005. });
  52006. Object.defineProperty(Animatable.prototype, "weight", {
  52007. /**
  52008. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52009. */
  52010. get: function () {
  52011. return this._weight;
  52012. },
  52013. set: function (value) {
  52014. if (value === -1) { // -1 is ok and means no weight
  52015. this._weight = -1;
  52016. return;
  52017. }
  52018. // Else weight must be in [0, 1] range
  52019. this._weight = Math.min(Math.max(value, 0), 1.0);
  52020. },
  52021. enumerable: true,
  52022. configurable: true
  52023. });
  52024. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52025. /**
  52026. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52027. */
  52028. get: function () {
  52029. return this._speedRatio;
  52030. },
  52031. set: function (value) {
  52032. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52033. var animation = this._runtimeAnimations[index];
  52034. animation._prepareForSpeedRatioChange(value);
  52035. }
  52036. this._speedRatio = value;
  52037. },
  52038. enumerable: true,
  52039. configurable: true
  52040. });
  52041. // Methods
  52042. /**
  52043. * Synchronize and normalize current Animatable with a source Animatable
  52044. * This is useful when using animation weights and when animations are not of the same length
  52045. * @param root defines the root Animatable to synchronize with
  52046. * @returns the current Animatable
  52047. */
  52048. Animatable.prototype.syncWith = function (root) {
  52049. this._syncRoot = root;
  52050. if (root) {
  52051. // Make sure this animatable will animate after the root
  52052. var index = this._scene._activeAnimatables.indexOf(this);
  52053. if (index > -1) {
  52054. this._scene._activeAnimatables.splice(index, 1);
  52055. this._scene._activeAnimatables.push(this);
  52056. }
  52057. }
  52058. return this;
  52059. };
  52060. Animatable.prototype.getAnimations = function () {
  52061. return this._runtimeAnimations;
  52062. };
  52063. Animatable.prototype.appendAnimations = function (target, animations) {
  52064. for (var index = 0; index < animations.length; index++) {
  52065. var animation = animations[index];
  52066. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52067. }
  52068. };
  52069. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52070. var runtimeAnimations = this._runtimeAnimations;
  52071. for (var index = 0; index < runtimeAnimations.length; index++) {
  52072. if (runtimeAnimations[index].animation.targetProperty === property) {
  52073. return runtimeAnimations[index].animation;
  52074. }
  52075. }
  52076. return null;
  52077. };
  52078. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52079. var runtimeAnimations = this._runtimeAnimations;
  52080. for (var index = 0; index < runtimeAnimations.length; index++) {
  52081. if (runtimeAnimations[index].animation.targetProperty === property) {
  52082. return runtimeAnimations[index];
  52083. }
  52084. }
  52085. return null;
  52086. };
  52087. Animatable.prototype.reset = function () {
  52088. var runtimeAnimations = this._runtimeAnimations;
  52089. for (var index = 0; index < runtimeAnimations.length; index++) {
  52090. runtimeAnimations[index].reset();
  52091. }
  52092. // Reset to original value
  52093. for (index = 0; index < runtimeAnimations.length; index++) {
  52094. var animation = runtimeAnimations[index];
  52095. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  52096. }
  52097. this._localDelayOffset = null;
  52098. this._pausedDelay = null;
  52099. };
  52100. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52101. var runtimeAnimations = this._runtimeAnimations;
  52102. for (var index = 0; index < runtimeAnimations.length; index++) {
  52103. runtimeAnimations[index].animation.enableBlending = true;
  52104. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52105. }
  52106. };
  52107. Animatable.prototype.disableBlending = function () {
  52108. var runtimeAnimations = this._runtimeAnimations;
  52109. for (var index = 0; index < runtimeAnimations.length; index++) {
  52110. runtimeAnimations[index].animation.enableBlending = false;
  52111. }
  52112. };
  52113. Animatable.prototype.goToFrame = function (frame) {
  52114. var runtimeAnimations = this._runtimeAnimations;
  52115. if (runtimeAnimations[0]) {
  52116. var fps = runtimeAnimations[0].animation.framePerSecond;
  52117. var currentFrame = runtimeAnimations[0].currentFrame;
  52118. var adjustTime = frame - currentFrame;
  52119. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52120. if (this._localDelayOffset === null) {
  52121. this._localDelayOffset = 0;
  52122. }
  52123. this._localDelayOffset -= delay;
  52124. }
  52125. for (var index = 0; index < runtimeAnimations.length; index++) {
  52126. runtimeAnimations[index].goToFrame(frame);
  52127. }
  52128. };
  52129. Animatable.prototype.pause = function () {
  52130. if (this._paused) {
  52131. return;
  52132. }
  52133. this._paused = true;
  52134. };
  52135. Animatable.prototype.restart = function () {
  52136. this._paused = false;
  52137. };
  52138. Animatable.prototype.stop = function (animationName) {
  52139. if (animationName) {
  52140. var idx = this._scene._activeAnimatables.indexOf(this);
  52141. if (idx > -1) {
  52142. var runtimeAnimations = this._runtimeAnimations;
  52143. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52144. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52145. continue;
  52146. }
  52147. runtimeAnimations[index].dispose();
  52148. runtimeAnimations.splice(index, 1);
  52149. }
  52150. if (runtimeAnimations.length == 0) {
  52151. this._scene._activeAnimatables.splice(idx, 1);
  52152. if (this.onAnimationEnd) {
  52153. this.onAnimationEnd();
  52154. }
  52155. }
  52156. }
  52157. }
  52158. else {
  52159. var index = this._scene._activeAnimatables.indexOf(this);
  52160. if (index > -1) {
  52161. this._scene._activeAnimatables.splice(index, 1);
  52162. var runtimeAnimations = this._runtimeAnimations;
  52163. for (var index = 0; index < runtimeAnimations.length; index++) {
  52164. runtimeAnimations[index].dispose();
  52165. }
  52166. if (this.onAnimationEnd) {
  52167. this.onAnimationEnd();
  52168. }
  52169. }
  52170. }
  52171. };
  52172. Animatable.prototype._animate = function (delay) {
  52173. if (this._paused) {
  52174. this.animationStarted = false;
  52175. if (this._pausedDelay === null) {
  52176. this._pausedDelay = delay;
  52177. }
  52178. return true;
  52179. }
  52180. if (this._localDelayOffset === null) {
  52181. this._localDelayOffset = delay;
  52182. this._pausedDelay = null;
  52183. }
  52184. else if (this._pausedDelay !== null) {
  52185. this._localDelayOffset += delay - this._pausedDelay;
  52186. this._pausedDelay = null;
  52187. }
  52188. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52189. return true;
  52190. }
  52191. // Animating
  52192. var running = false;
  52193. var runtimeAnimations = this._runtimeAnimations;
  52194. var index;
  52195. for (index = 0; index < runtimeAnimations.length; index++) {
  52196. var animation = runtimeAnimations[index];
  52197. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52198. running = running || isRunning;
  52199. }
  52200. this.animationStarted = running;
  52201. if (!running) {
  52202. // Remove from active animatables
  52203. index = this._scene._activeAnimatables.indexOf(this);
  52204. this._scene._activeAnimatables.splice(index, 1);
  52205. // Dispose all runtime animations
  52206. for (index = 0; index < runtimeAnimations.length; index++) {
  52207. runtimeAnimations[index].dispose();
  52208. }
  52209. }
  52210. if (!running && this.onAnimationEnd) {
  52211. this.onAnimationEnd();
  52212. this.onAnimationEnd = null;
  52213. }
  52214. return running;
  52215. };
  52216. return Animatable;
  52217. }());
  52218. BABYLON.Animatable = Animatable;
  52219. })(BABYLON || (BABYLON = {}));
  52220. //# sourceMappingURL=babylon.animatable.js.map
  52221. var BABYLON;
  52222. (function (BABYLON) {
  52223. var EasingFunction = /** @class */ (function () {
  52224. function EasingFunction() {
  52225. // Properties
  52226. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52227. }
  52228. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52229. get: function () {
  52230. return EasingFunction._EASINGMODE_EASEIN;
  52231. },
  52232. enumerable: true,
  52233. configurable: true
  52234. });
  52235. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52236. get: function () {
  52237. return EasingFunction._EASINGMODE_EASEOUT;
  52238. },
  52239. enumerable: true,
  52240. configurable: true
  52241. });
  52242. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52243. get: function () {
  52244. return EasingFunction._EASINGMODE_EASEINOUT;
  52245. },
  52246. enumerable: true,
  52247. configurable: true
  52248. });
  52249. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52250. var n = Math.min(Math.max(easingMode, 0), 2);
  52251. this._easingMode = n;
  52252. };
  52253. EasingFunction.prototype.getEasingMode = function () {
  52254. return this._easingMode;
  52255. };
  52256. EasingFunction.prototype.easeInCore = function (gradient) {
  52257. throw new Error('You must implement this method');
  52258. };
  52259. EasingFunction.prototype.ease = function (gradient) {
  52260. switch (this._easingMode) {
  52261. case EasingFunction.EASINGMODE_EASEIN:
  52262. return this.easeInCore(gradient);
  52263. case EasingFunction.EASINGMODE_EASEOUT:
  52264. return (1 - this.easeInCore(1 - gradient));
  52265. }
  52266. if (gradient >= 0.5) {
  52267. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52268. }
  52269. return (this.easeInCore(gradient * 2) * 0.5);
  52270. };
  52271. //Statics
  52272. EasingFunction._EASINGMODE_EASEIN = 0;
  52273. EasingFunction._EASINGMODE_EASEOUT = 1;
  52274. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52275. return EasingFunction;
  52276. }());
  52277. BABYLON.EasingFunction = EasingFunction;
  52278. var CircleEase = /** @class */ (function (_super) {
  52279. __extends(CircleEase, _super);
  52280. function CircleEase() {
  52281. return _super !== null && _super.apply(this, arguments) || this;
  52282. }
  52283. CircleEase.prototype.easeInCore = function (gradient) {
  52284. gradient = Math.max(0, Math.min(1, gradient));
  52285. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52286. };
  52287. return CircleEase;
  52288. }(EasingFunction));
  52289. BABYLON.CircleEase = CircleEase;
  52290. var BackEase = /** @class */ (function (_super) {
  52291. __extends(BackEase, _super);
  52292. function BackEase(amplitude) {
  52293. if (amplitude === void 0) { amplitude = 1; }
  52294. var _this = _super.call(this) || this;
  52295. _this.amplitude = amplitude;
  52296. return _this;
  52297. }
  52298. BackEase.prototype.easeInCore = function (gradient) {
  52299. var num = Math.max(0, this.amplitude);
  52300. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52301. };
  52302. return BackEase;
  52303. }(EasingFunction));
  52304. BABYLON.BackEase = BackEase;
  52305. var BounceEase = /** @class */ (function (_super) {
  52306. __extends(BounceEase, _super);
  52307. function BounceEase(bounces, bounciness) {
  52308. if (bounces === void 0) { bounces = 3; }
  52309. if (bounciness === void 0) { bounciness = 2; }
  52310. var _this = _super.call(this) || this;
  52311. _this.bounces = bounces;
  52312. _this.bounciness = bounciness;
  52313. return _this;
  52314. }
  52315. BounceEase.prototype.easeInCore = function (gradient) {
  52316. var y = Math.max(0.0, this.bounces);
  52317. var bounciness = this.bounciness;
  52318. if (bounciness <= 1.0) {
  52319. bounciness = 1.001;
  52320. }
  52321. var num9 = Math.pow(bounciness, y);
  52322. var num5 = 1.0 - bounciness;
  52323. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52324. var num15 = gradient * num4;
  52325. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52326. var num3 = Math.floor(num65);
  52327. var num13 = num3 + 1.0;
  52328. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52329. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52330. var num7 = (num8 + num12) * 0.5;
  52331. var num6 = gradient - num7;
  52332. var num2 = num7 - num8;
  52333. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52334. };
  52335. return BounceEase;
  52336. }(EasingFunction));
  52337. BABYLON.BounceEase = BounceEase;
  52338. var CubicEase = /** @class */ (function (_super) {
  52339. __extends(CubicEase, _super);
  52340. function CubicEase() {
  52341. return _super !== null && _super.apply(this, arguments) || this;
  52342. }
  52343. CubicEase.prototype.easeInCore = function (gradient) {
  52344. return (gradient * gradient * gradient);
  52345. };
  52346. return CubicEase;
  52347. }(EasingFunction));
  52348. BABYLON.CubicEase = CubicEase;
  52349. var ElasticEase = /** @class */ (function (_super) {
  52350. __extends(ElasticEase, _super);
  52351. function ElasticEase(oscillations, springiness) {
  52352. if (oscillations === void 0) { oscillations = 3; }
  52353. if (springiness === void 0) { springiness = 3; }
  52354. var _this = _super.call(this) || this;
  52355. _this.oscillations = oscillations;
  52356. _this.springiness = springiness;
  52357. return _this;
  52358. }
  52359. ElasticEase.prototype.easeInCore = function (gradient) {
  52360. var num2;
  52361. var num3 = Math.max(0.0, this.oscillations);
  52362. var num = Math.max(0.0, this.springiness);
  52363. if (num == 0) {
  52364. num2 = gradient;
  52365. }
  52366. else {
  52367. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52368. }
  52369. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52370. };
  52371. return ElasticEase;
  52372. }(EasingFunction));
  52373. BABYLON.ElasticEase = ElasticEase;
  52374. var ExponentialEase = /** @class */ (function (_super) {
  52375. __extends(ExponentialEase, _super);
  52376. function ExponentialEase(exponent) {
  52377. if (exponent === void 0) { exponent = 2; }
  52378. var _this = _super.call(this) || this;
  52379. _this.exponent = exponent;
  52380. return _this;
  52381. }
  52382. ExponentialEase.prototype.easeInCore = function (gradient) {
  52383. if (this.exponent <= 0) {
  52384. return gradient;
  52385. }
  52386. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52387. };
  52388. return ExponentialEase;
  52389. }(EasingFunction));
  52390. BABYLON.ExponentialEase = ExponentialEase;
  52391. var PowerEase = /** @class */ (function (_super) {
  52392. __extends(PowerEase, _super);
  52393. function PowerEase(power) {
  52394. if (power === void 0) { power = 2; }
  52395. var _this = _super.call(this) || this;
  52396. _this.power = power;
  52397. return _this;
  52398. }
  52399. PowerEase.prototype.easeInCore = function (gradient) {
  52400. var y = Math.max(0.0, this.power);
  52401. return Math.pow(gradient, y);
  52402. };
  52403. return PowerEase;
  52404. }(EasingFunction));
  52405. BABYLON.PowerEase = PowerEase;
  52406. var QuadraticEase = /** @class */ (function (_super) {
  52407. __extends(QuadraticEase, _super);
  52408. function QuadraticEase() {
  52409. return _super !== null && _super.apply(this, arguments) || this;
  52410. }
  52411. QuadraticEase.prototype.easeInCore = function (gradient) {
  52412. return (gradient * gradient);
  52413. };
  52414. return QuadraticEase;
  52415. }(EasingFunction));
  52416. BABYLON.QuadraticEase = QuadraticEase;
  52417. var QuarticEase = /** @class */ (function (_super) {
  52418. __extends(QuarticEase, _super);
  52419. function QuarticEase() {
  52420. return _super !== null && _super.apply(this, arguments) || this;
  52421. }
  52422. QuarticEase.prototype.easeInCore = function (gradient) {
  52423. return (gradient * gradient * gradient * gradient);
  52424. };
  52425. return QuarticEase;
  52426. }(EasingFunction));
  52427. BABYLON.QuarticEase = QuarticEase;
  52428. var QuinticEase = /** @class */ (function (_super) {
  52429. __extends(QuinticEase, _super);
  52430. function QuinticEase() {
  52431. return _super !== null && _super.apply(this, arguments) || this;
  52432. }
  52433. QuinticEase.prototype.easeInCore = function (gradient) {
  52434. return (gradient * gradient * gradient * gradient * gradient);
  52435. };
  52436. return QuinticEase;
  52437. }(EasingFunction));
  52438. BABYLON.QuinticEase = QuinticEase;
  52439. var SineEase = /** @class */ (function (_super) {
  52440. __extends(SineEase, _super);
  52441. function SineEase() {
  52442. return _super !== null && _super.apply(this, arguments) || this;
  52443. }
  52444. SineEase.prototype.easeInCore = function (gradient) {
  52445. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52446. };
  52447. return SineEase;
  52448. }(EasingFunction));
  52449. BABYLON.SineEase = SineEase;
  52450. var BezierCurveEase = /** @class */ (function (_super) {
  52451. __extends(BezierCurveEase, _super);
  52452. function BezierCurveEase(x1, y1, x2, y2) {
  52453. if (x1 === void 0) { x1 = 0; }
  52454. if (y1 === void 0) { y1 = 0; }
  52455. if (x2 === void 0) { x2 = 1; }
  52456. if (y2 === void 0) { y2 = 1; }
  52457. var _this = _super.call(this) || this;
  52458. _this.x1 = x1;
  52459. _this.y1 = y1;
  52460. _this.x2 = x2;
  52461. _this.y2 = y2;
  52462. return _this;
  52463. }
  52464. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52465. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52466. };
  52467. return BezierCurveEase;
  52468. }(EasingFunction));
  52469. BABYLON.BezierCurveEase = BezierCurveEase;
  52470. })(BABYLON || (BABYLON = {}));
  52471. //# sourceMappingURL=babylon.easing.js.map
  52472. var BABYLON;
  52473. (function (BABYLON) {
  52474. /**
  52475. * A Condition applied to an Action
  52476. */
  52477. var Condition = /** @class */ (function () {
  52478. /**
  52479. * Creates a new Condition
  52480. * @param actionManager the manager of the action the condition is applied to
  52481. */
  52482. function Condition(actionManager) {
  52483. this._actionManager = actionManager;
  52484. }
  52485. /**
  52486. * Check if the current condition is valid
  52487. * @returns a boolean
  52488. */
  52489. Condition.prototype.isValid = function () {
  52490. return true;
  52491. };
  52492. /**
  52493. * Internal only
  52494. * @hidden
  52495. */
  52496. Condition.prototype._getProperty = function (propertyPath) {
  52497. return this._actionManager._getProperty(propertyPath);
  52498. };
  52499. /**
  52500. * Internal only
  52501. * @hidden
  52502. */
  52503. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52504. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52505. };
  52506. /**
  52507. * Serialize placeholder for child classes
  52508. * @returns the serialized object
  52509. */
  52510. Condition.prototype.serialize = function () {
  52511. };
  52512. /**
  52513. * Internal only
  52514. * @hidden
  52515. */
  52516. Condition.prototype._serialize = function (serializedCondition) {
  52517. return {
  52518. type: 2,
  52519. children: [],
  52520. name: serializedCondition.name,
  52521. properties: serializedCondition.properties
  52522. };
  52523. };
  52524. return Condition;
  52525. }());
  52526. BABYLON.Condition = Condition;
  52527. /**
  52528. * Defines specific conditional operators as extensions of Condition
  52529. */
  52530. var ValueCondition = /** @class */ (function (_super) {
  52531. __extends(ValueCondition, _super);
  52532. /**
  52533. * Creates a new ValueCondition
  52534. * @param actionManager manager for the action the condition applies to
  52535. * @param target for the action
  52536. * @param propertyPath path to specify the property of the target the conditional operator uses
  52537. * @param value the value compared by the conditional operator against the current value of the property
  52538. * @param operator the conditional operator, default ValueCondition.IsEqual
  52539. */
  52540. function ValueCondition(actionManager, target,
  52541. /** path to specify the property of the target the conditional operator uses */
  52542. propertyPath,
  52543. /** the value compared by the conditional operator against the current value of the property */
  52544. value,
  52545. /** the conditional operator, default ValueCondition.IsEqual */
  52546. operator) {
  52547. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52548. var _this = _super.call(this, actionManager) || this;
  52549. _this.propertyPath = propertyPath;
  52550. _this.value = value;
  52551. _this.operator = operator;
  52552. _this._target = target;
  52553. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52554. _this._property = _this._getProperty(_this.propertyPath);
  52555. return _this;
  52556. }
  52557. Object.defineProperty(ValueCondition, "IsEqual", {
  52558. /**
  52559. * returns the number for IsEqual
  52560. */
  52561. get: function () {
  52562. return ValueCondition._IsEqual;
  52563. },
  52564. enumerable: true,
  52565. configurable: true
  52566. });
  52567. Object.defineProperty(ValueCondition, "IsDifferent", {
  52568. /**
  52569. * Returns the number for IsDifferent
  52570. */
  52571. get: function () {
  52572. return ValueCondition._IsDifferent;
  52573. },
  52574. enumerable: true,
  52575. configurable: true
  52576. });
  52577. Object.defineProperty(ValueCondition, "IsGreater", {
  52578. /**
  52579. * Returns the number for IsGreater
  52580. */
  52581. get: function () {
  52582. return ValueCondition._IsGreater;
  52583. },
  52584. enumerable: true,
  52585. configurable: true
  52586. });
  52587. Object.defineProperty(ValueCondition, "IsLesser", {
  52588. /**
  52589. * Returns the number for IsLesser
  52590. */
  52591. get: function () {
  52592. return ValueCondition._IsLesser;
  52593. },
  52594. enumerable: true,
  52595. configurable: true
  52596. });
  52597. /**
  52598. * Compares the given value with the property value for the specified conditional operator
  52599. * @returns the result of the comparison
  52600. */
  52601. ValueCondition.prototype.isValid = function () {
  52602. switch (this.operator) {
  52603. case ValueCondition.IsGreater:
  52604. return this._effectiveTarget[this._property] > this.value;
  52605. case ValueCondition.IsLesser:
  52606. return this._effectiveTarget[this._property] < this.value;
  52607. case ValueCondition.IsEqual:
  52608. case ValueCondition.IsDifferent:
  52609. var check;
  52610. if (this.value.equals) {
  52611. check = this.value.equals(this._effectiveTarget[this._property]);
  52612. }
  52613. else {
  52614. check = this.value === this._effectiveTarget[this._property];
  52615. }
  52616. return this.operator === ValueCondition.IsEqual ? check : !check;
  52617. }
  52618. return false;
  52619. };
  52620. /**
  52621. * Serialize the ValueCondition into a JSON compatible object
  52622. * @returns serialization object
  52623. */
  52624. ValueCondition.prototype.serialize = function () {
  52625. return this._serialize({
  52626. name: "ValueCondition",
  52627. properties: [
  52628. BABYLON.Action._GetTargetProperty(this._target),
  52629. { name: "propertyPath", value: this.propertyPath },
  52630. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52631. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52632. ]
  52633. });
  52634. };
  52635. /**
  52636. * Gets the name of the conditional operator for the ValueCondition
  52637. * @param operator the conditional operator
  52638. * @returns the name
  52639. */
  52640. ValueCondition.GetOperatorName = function (operator) {
  52641. switch (operator) {
  52642. case ValueCondition._IsEqual: return "IsEqual";
  52643. case ValueCondition._IsDifferent: return "IsDifferent";
  52644. case ValueCondition._IsGreater: return "IsGreater";
  52645. case ValueCondition._IsLesser: return "IsLesser";
  52646. default: return "";
  52647. }
  52648. };
  52649. /**
  52650. * Internal only
  52651. * @hidden
  52652. */
  52653. ValueCondition._IsEqual = 0;
  52654. /**
  52655. * Internal only
  52656. * @hidden
  52657. */
  52658. ValueCondition._IsDifferent = 1;
  52659. /**
  52660. * Internal only
  52661. * @hidden
  52662. */
  52663. ValueCondition._IsGreater = 2;
  52664. /**
  52665. * Internal only
  52666. * @hidden
  52667. */
  52668. ValueCondition._IsLesser = 3;
  52669. return ValueCondition;
  52670. }(Condition));
  52671. BABYLON.ValueCondition = ValueCondition;
  52672. /**
  52673. * Defines a predicate condition as an extension of Condition
  52674. */
  52675. var PredicateCondition = /** @class */ (function (_super) {
  52676. __extends(PredicateCondition, _super);
  52677. /**
  52678. * Creates a new PredicateCondition
  52679. * @param actionManager manager for the action the condition applies to
  52680. * @param predicate defines the predicate function used to validate the condition
  52681. */
  52682. function PredicateCondition(actionManager,
  52683. /** defines the predicate function used to validate the condition */
  52684. predicate) {
  52685. var _this = _super.call(this, actionManager) || this;
  52686. _this.predicate = predicate;
  52687. return _this;
  52688. }
  52689. /**
  52690. * @returns the validity of the predicate condition
  52691. */
  52692. PredicateCondition.prototype.isValid = function () {
  52693. return this.predicate();
  52694. };
  52695. return PredicateCondition;
  52696. }(Condition));
  52697. BABYLON.PredicateCondition = PredicateCondition;
  52698. /**
  52699. * Defines a state condition as an extension of Condition
  52700. */
  52701. var StateCondition = /** @class */ (function (_super) {
  52702. __extends(StateCondition, _super);
  52703. /**
  52704. * Creates a new StateCondition
  52705. * @param actionManager manager for the action the condition applies to
  52706. * @param target of the condition
  52707. * @param value to compare with target state
  52708. */
  52709. function StateCondition(actionManager, target, value) {
  52710. var _this = _super.call(this, actionManager) || this;
  52711. _this.value = value;
  52712. _this._target = target;
  52713. return _this;
  52714. }
  52715. /**
  52716. * @returns the validity of the state
  52717. */
  52718. StateCondition.prototype.isValid = function () {
  52719. return this._target.state === this.value;
  52720. };
  52721. /**
  52722. * Serialize the StateCondition into a JSON compatible object
  52723. * @returns serialization object
  52724. */
  52725. StateCondition.prototype.serialize = function () {
  52726. return this._serialize({
  52727. name: "StateCondition",
  52728. properties: [
  52729. BABYLON.Action._GetTargetProperty(this._target),
  52730. { name: "value", value: this.value }
  52731. ]
  52732. });
  52733. };
  52734. return StateCondition;
  52735. }(Condition));
  52736. BABYLON.StateCondition = StateCondition;
  52737. })(BABYLON || (BABYLON = {}));
  52738. //# sourceMappingURL=babylon.condition.js.map
  52739. var BABYLON;
  52740. (function (BABYLON) {
  52741. /**
  52742. * The action to be carried out following a trigger
  52743. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52744. */
  52745. var Action = /** @class */ (function () {
  52746. /**
  52747. * Creates a new Action
  52748. * @param triggerOptions the trigger, with or without parameters, for the action
  52749. * @param condition an optional determinant of action
  52750. */
  52751. function Action(
  52752. /** the trigger, with or without parameters, for the action */
  52753. triggerOptions, condition) {
  52754. this.triggerOptions = triggerOptions;
  52755. /**
  52756. * An event triggered prior to action being executed.
  52757. */
  52758. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52759. if (triggerOptions.parameter) {
  52760. this.trigger = triggerOptions.trigger;
  52761. this._triggerParameter = triggerOptions.parameter;
  52762. }
  52763. else {
  52764. this.trigger = triggerOptions;
  52765. }
  52766. this._nextActiveAction = this;
  52767. this._condition = condition;
  52768. }
  52769. /**
  52770. * Internal only
  52771. * @hidden
  52772. */
  52773. Action.prototype._prepare = function () {
  52774. };
  52775. /**
  52776. * Gets the trigger parameters
  52777. * @returns the trigger parameters
  52778. */
  52779. Action.prototype.getTriggerParameter = function () {
  52780. return this._triggerParameter;
  52781. };
  52782. /**
  52783. * Internal only - executes current action event
  52784. * @hidden
  52785. */
  52786. Action.prototype._executeCurrent = function (evt) {
  52787. if (this._nextActiveAction._condition) {
  52788. var condition = this._nextActiveAction._condition;
  52789. var currentRenderId = this._actionManager.getScene().getRenderId();
  52790. // We cache the current evaluation for the current frame
  52791. if (condition._evaluationId === currentRenderId) {
  52792. if (!condition._currentResult) {
  52793. return;
  52794. }
  52795. }
  52796. else {
  52797. condition._evaluationId = currentRenderId;
  52798. if (!condition.isValid()) {
  52799. condition._currentResult = false;
  52800. return;
  52801. }
  52802. condition._currentResult = true;
  52803. }
  52804. }
  52805. this.onBeforeExecuteObservable.notifyObservers(this);
  52806. this._nextActiveAction.execute(evt);
  52807. this.skipToNextActiveAction();
  52808. };
  52809. /**
  52810. * Execute placeholder for child classes
  52811. * @param evt optional action event
  52812. */
  52813. Action.prototype.execute = function (evt) {
  52814. };
  52815. /**
  52816. * Skips to next active action
  52817. */
  52818. Action.prototype.skipToNextActiveAction = function () {
  52819. if (this._nextActiveAction._child) {
  52820. if (!this._nextActiveAction._child._actionManager) {
  52821. this._nextActiveAction._child._actionManager = this._actionManager;
  52822. }
  52823. this._nextActiveAction = this._nextActiveAction._child;
  52824. }
  52825. else {
  52826. this._nextActiveAction = this;
  52827. }
  52828. };
  52829. /**
  52830. * Adds action to chain of actions, may be a DoNothingAction
  52831. * @param action defines the next action to execute
  52832. * @returns The action passed in
  52833. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52834. */
  52835. Action.prototype.then = function (action) {
  52836. this._child = action;
  52837. action._actionManager = this._actionManager;
  52838. action._prepare();
  52839. return action;
  52840. };
  52841. /**
  52842. * Internal only
  52843. * @hidden
  52844. */
  52845. Action.prototype._getProperty = function (propertyPath) {
  52846. return this._actionManager._getProperty(propertyPath);
  52847. };
  52848. /**
  52849. * Internal only
  52850. * @hidden
  52851. */
  52852. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52853. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52854. };
  52855. /**
  52856. * Serialize placeholder for child classes
  52857. * @param parent of child
  52858. * @returns the serialized object
  52859. */
  52860. Action.prototype.serialize = function (parent) {
  52861. };
  52862. /**
  52863. * Internal only called by serialize
  52864. * @hidden
  52865. */
  52866. Action.prototype._serialize = function (serializedAction, parent) {
  52867. var serializationObject = {
  52868. type: 1,
  52869. children: [],
  52870. name: serializedAction.name,
  52871. properties: serializedAction.properties || []
  52872. };
  52873. // Serialize child
  52874. if (this._child) {
  52875. this._child.serialize(serializationObject);
  52876. }
  52877. // Check if "this" has a condition
  52878. if (this._condition) {
  52879. var serializedCondition = this._condition.serialize();
  52880. serializedCondition.children.push(serializationObject);
  52881. if (parent) {
  52882. parent.children.push(serializedCondition);
  52883. }
  52884. return serializedCondition;
  52885. }
  52886. if (parent) {
  52887. parent.children.push(serializationObject);
  52888. }
  52889. return serializationObject;
  52890. };
  52891. /**
  52892. * Internal only
  52893. * @hidden
  52894. */
  52895. Action._SerializeValueAsString = function (value) {
  52896. if (typeof value === "number") {
  52897. return value.toString();
  52898. }
  52899. if (typeof value === "boolean") {
  52900. return value ? "true" : "false";
  52901. }
  52902. if (value instanceof BABYLON.Vector2) {
  52903. return value.x + ", " + value.y;
  52904. }
  52905. if (value instanceof BABYLON.Vector3) {
  52906. return value.x + ", " + value.y + ", " + value.z;
  52907. }
  52908. if (value instanceof BABYLON.Color3) {
  52909. return value.r + ", " + value.g + ", " + value.b;
  52910. }
  52911. if (value instanceof BABYLON.Color4) {
  52912. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52913. }
  52914. return value; // string
  52915. };
  52916. /**
  52917. * Internal only
  52918. * @hidden
  52919. */
  52920. Action._GetTargetProperty = function (target) {
  52921. return {
  52922. name: "target",
  52923. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52924. : target instanceof BABYLON.Light ? "LightProperties"
  52925. : target instanceof BABYLON.Camera ? "CameraProperties"
  52926. : "SceneProperties",
  52927. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52928. };
  52929. };
  52930. return Action;
  52931. }());
  52932. BABYLON.Action = Action;
  52933. })(BABYLON || (BABYLON = {}));
  52934. //# sourceMappingURL=babylon.action.js.map
  52935. var BABYLON;
  52936. (function (BABYLON) {
  52937. /**
  52938. * ActionEvent is the event being sent when an action is triggered.
  52939. */
  52940. var ActionEvent = /** @class */ (function () {
  52941. /**
  52942. * Creates a new ActionEvent
  52943. * @param source The mesh or sprite that triggered the action
  52944. * @param pointerX The X mouse cursor position at the time of the event
  52945. * @param pointerY The Y mouse cursor position at the time of the event
  52946. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52947. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52948. * @param additionalData additional data for the event
  52949. */
  52950. function ActionEvent(
  52951. /** The mesh or sprite that triggered the action */
  52952. source,
  52953. /** The X mouse cursor position at the time of the event */
  52954. pointerX,
  52955. /** The Y mouse cursor position at the time of the event */
  52956. pointerY,
  52957. /** The mesh that is currently pointed at (can be null) */
  52958. meshUnderPointer,
  52959. /** the original (browser) event that triggered the ActionEvent */
  52960. sourceEvent,
  52961. /** additional data for the event */
  52962. additionalData) {
  52963. this.source = source;
  52964. this.pointerX = pointerX;
  52965. this.pointerY = pointerY;
  52966. this.meshUnderPointer = meshUnderPointer;
  52967. this.sourceEvent = sourceEvent;
  52968. this.additionalData = additionalData;
  52969. }
  52970. /**
  52971. * Helper function to auto-create an ActionEvent from a source mesh.
  52972. * @param source The source mesh that triggered the event
  52973. * @param evt The original (browser) event
  52974. * @param additionalData additional data for the event
  52975. * @returns the new ActionEvent
  52976. */
  52977. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52978. var scene = source.getScene();
  52979. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52980. };
  52981. /**
  52982. * Helper function to auto-create an ActionEvent from a source sprite
  52983. * @param source The source sprite that triggered the event
  52984. * @param scene Scene associated with the sprite
  52985. * @param evt The original (browser) event
  52986. * @param additionalData additional data for the event
  52987. * @returns the new ActionEvent
  52988. */
  52989. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52990. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52991. };
  52992. /**
  52993. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52994. * @param scene the scene where the event occurred
  52995. * @param evt The original (browser) event
  52996. * @returns the new ActionEvent
  52997. */
  52998. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52999. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53000. };
  53001. /**
  53002. * Helper function to auto-create an ActionEvent from a primitive
  53003. * @param prim defines the target primitive
  53004. * @param pointerPos defines the pointer position
  53005. * @param evt The original (browser) event
  53006. * @param additionalData additional data for the event
  53007. * @returns the new ActionEvent
  53008. */
  53009. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53010. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53011. };
  53012. return ActionEvent;
  53013. }());
  53014. BABYLON.ActionEvent = ActionEvent;
  53015. /**
  53016. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53017. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53018. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53019. */
  53020. var ActionManager = /** @class */ (function () {
  53021. /**
  53022. * Creates a new action manager
  53023. * @param scene defines the hosting scene
  53024. */
  53025. function ActionManager(scene) {
  53026. // Members
  53027. /** Gets the list of actions */
  53028. this.actions = new Array();
  53029. /** Gets the cursor to use when hovering items */
  53030. this.hoverCursor = '';
  53031. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53032. scene._actionManagers.push(this);
  53033. }
  53034. Object.defineProperty(ActionManager, "NothingTrigger", {
  53035. /**
  53036. * Nothing
  53037. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53038. */
  53039. get: function () {
  53040. return ActionManager._NothingTrigger;
  53041. },
  53042. enumerable: true,
  53043. configurable: true
  53044. });
  53045. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53046. /**
  53047. * On pick
  53048. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53049. */
  53050. get: function () {
  53051. return ActionManager._OnPickTrigger;
  53052. },
  53053. enumerable: true,
  53054. configurable: true
  53055. });
  53056. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53057. /**
  53058. * On left pick
  53059. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53060. */
  53061. get: function () {
  53062. return ActionManager._OnLeftPickTrigger;
  53063. },
  53064. enumerable: true,
  53065. configurable: true
  53066. });
  53067. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53068. /**
  53069. * On right pick
  53070. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53071. */
  53072. get: function () {
  53073. return ActionManager._OnRightPickTrigger;
  53074. },
  53075. enumerable: true,
  53076. configurable: true
  53077. });
  53078. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53079. /**
  53080. * On center pick
  53081. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53082. */
  53083. get: function () {
  53084. return ActionManager._OnCenterPickTrigger;
  53085. },
  53086. enumerable: true,
  53087. configurable: true
  53088. });
  53089. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53090. /**
  53091. * On pick down
  53092. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53093. */
  53094. get: function () {
  53095. return ActionManager._OnPickDownTrigger;
  53096. },
  53097. enumerable: true,
  53098. configurable: true
  53099. });
  53100. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53101. /**
  53102. * On double pick
  53103. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53104. */
  53105. get: function () {
  53106. return ActionManager._OnDoublePickTrigger;
  53107. },
  53108. enumerable: true,
  53109. configurable: true
  53110. });
  53111. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53112. /**
  53113. * On pick up
  53114. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53115. */
  53116. get: function () {
  53117. return ActionManager._OnPickUpTrigger;
  53118. },
  53119. enumerable: true,
  53120. configurable: true
  53121. });
  53122. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53123. /**
  53124. * On pick out.
  53125. * This trigger will only be raised if you also declared a OnPickDown
  53126. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53127. */
  53128. get: function () {
  53129. return ActionManager._OnPickOutTrigger;
  53130. },
  53131. enumerable: true,
  53132. configurable: true
  53133. });
  53134. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53135. /**
  53136. * On long press
  53137. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53138. */
  53139. get: function () {
  53140. return ActionManager._OnLongPressTrigger;
  53141. },
  53142. enumerable: true,
  53143. configurable: true
  53144. });
  53145. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53146. /**
  53147. * On pointer over
  53148. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53149. */
  53150. get: function () {
  53151. return ActionManager._OnPointerOverTrigger;
  53152. },
  53153. enumerable: true,
  53154. configurable: true
  53155. });
  53156. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53157. /**
  53158. * On pointer out
  53159. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53160. */
  53161. get: function () {
  53162. return ActionManager._OnPointerOutTrigger;
  53163. },
  53164. enumerable: true,
  53165. configurable: true
  53166. });
  53167. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53168. /**
  53169. * On every frame
  53170. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53171. */
  53172. get: function () {
  53173. return ActionManager._OnEveryFrameTrigger;
  53174. },
  53175. enumerable: true,
  53176. configurable: true
  53177. });
  53178. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53179. /**
  53180. * On intersection enter
  53181. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53182. */
  53183. get: function () {
  53184. return ActionManager._OnIntersectionEnterTrigger;
  53185. },
  53186. enumerable: true,
  53187. configurable: true
  53188. });
  53189. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53190. /**
  53191. * On intersection exit
  53192. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53193. */
  53194. get: function () {
  53195. return ActionManager._OnIntersectionExitTrigger;
  53196. },
  53197. enumerable: true,
  53198. configurable: true
  53199. });
  53200. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53201. /**
  53202. * On key down
  53203. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53204. */
  53205. get: function () {
  53206. return ActionManager._OnKeyDownTrigger;
  53207. },
  53208. enumerable: true,
  53209. configurable: true
  53210. });
  53211. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53212. /**
  53213. * On key up
  53214. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53215. */
  53216. get: function () {
  53217. return ActionManager._OnKeyUpTrigger;
  53218. },
  53219. enumerable: true,
  53220. configurable: true
  53221. });
  53222. // Methods
  53223. /**
  53224. * Releases all associated resources
  53225. */
  53226. ActionManager.prototype.dispose = function () {
  53227. var index = this._scene._actionManagers.indexOf(this);
  53228. for (var i = 0; i < this.actions.length; i++) {
  53229. var action = this.actions[i];
  53230. ActionManager.Triggers[action.trigger]--;
  53231. if (ActionManager.Triggers[action.trigger] === 0) {
  53232. delete ActionManager.Triggers[action.trigger];
  53233. }
  53234. }
  53235. if (index > -1) {
  53236. this._scene._actionManagers.splice(index, 1);
  53237. }
  53238. };
  53239. /**
  53240. * Gets hosting scene
  53241. * @returns the hosting scene
  53242. */
  53243. ActionManager.prototype.getScene = function () {
  53244. return this._scene;
  53245. };
  53246. /**
  53247. * Does this action manager handles actions of any of the given triggers
  53248. * @param triggers defines the triggers to be tested
  53249. * @return a boolean indicating whether one (or more) of the triggers is handled
  53250. */
  53251. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53252. for (var index = 0; index < this.actions.length; index++) {
  53253. var action = this.actions[index];
  53254. if (triggers.indexOf(action.trigger) > -1) {
  53255. return true;
  53256. }
  53257. }
  53258. return false;
  53259. };
  53260. /**
  53261. * Does this action manager handles actions of a given trigger
  53262. * @param trigger defines the trigger to be tested
  53263. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53264. * @return whether the trigger is handled
  53265. */
  53266. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53267. for (var index = 0; index < this.actions.length; index++) {
  53268. var action = this.actions[index];
  53269. if (action.trigger === trigger) {
  53270. if (parameterPredicate) {
  53271. if (parameterPredicate(action.getTriggerParameter())) {
  53272. return true;
  53273. }
  53274. }
  53275. else {
  53276. return true;
  53277. }
  53278. }
  53279. }
  53280. return false;
  53281. };
  53282. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53283. /**
  53284. * Does this action manager has pointer triggers
  53285. */
  53286. get: function () {
  53287. for (var index = 0; index < this.actions.length; index++) {
  53288. var action = this.actions[index];
  53289. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53290. return true;
  53291. }
  53292. }
  53293. return false;
  53294. },
  53295. enumerable: true,
  53296. configurable: true
  53297. });
  53298. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53299. /**
  53300. * Does this action manager has pick triggers
  53301. */
  53302. get: function () {
  53303. for (var index = 0; index < this.actions.length; index++) {
  53304. var action = this.actions[index];
  53305. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53306. return true;
  53307. }
  53308. }
  53309. return false;
  53310. },
  53311. enumerable: true,
  53312. configurable: true
  53313. });
  53314. Object.defineProperty(ActionManager, "HasTriggers", {
  53315. /**
  53316. * Does exist one action manager with at least one trigger
  53317. **/
  53318. get: function () {
  53319. for (var t in ActionManager.Triggers) {
  53320. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53321. return true;
  53322. }
  53323. }
  53324. return false;
  53325. },
  53326. enumerable: true,
  53327. configurable: true
  53328. });
  53329. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53330. /**
  53331. * Does exist one action manager with at least one pick trigger
  53332. **/
  53333. get: function () {
  53334. for (var t in ActionManager.Triggers) {
  53335. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53336. var t_int = parseInt(t);
  53337. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53338. return true;
  53339. }
  53340. }
  53341. }
  53342. return false;
  53343. },
  53344. enumerable: true,
  53345. configurable: true
  53346. });
  53347. /**
  53348. * Does exist one action manager that handles actions of a given trigger
  53349. * @param trigger defines the trigger to be tested
  53350. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53351. **/
  53352. ActionManager.HasSpecificTrigger = function (trigger) {
  53353. for (var t in ActionManager.Triggers) {
  53354. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53355. var t_int = parseInt(t);
  53356. if (t_int === trigger) {
  53357. return true;
  53358. }
  53359. }
  53360. }
  53361. return false;
  53362. };
  53363. /**
  53364. * Registers an action to this action manager
  53365. * @param action defines the action to be registered
  53366. * @return the action amended (prepared) after registration
  53367. */
  53368. ActionManager.prototype.registerAction = function (action) {
  53369. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53370. if (this.getScene().actionManager !== this) {
  53371. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53372. return null;
  53373. }
  53374. }
  53375. this.actions.push(action);
  53376. if (ActionManager.Triggers[action.trigger]) {
  53377. ActionManager.Triggers[action.trigger]++;
  53378. }
  53379. else {
  53380. ActionManager.Triggers[action.trigger] = 1;
  53381. }
  53382. action._actionManager = this;
  53383. action._prepare();
  53384. return action;
  53385. };
  53386. /**
  53387. * Unregisters an action to this action manager
  53388. * @param action defines the action to be unregistered
  53389. * @return a boolean indicating whether the action has been unregistered
  53390. */
  53391. ActionManager.prototype.unregisterAction = function (action) {
  53392. var index = this.actions.indexOf(action);
  53393. if (index !== -1) {
  53394. this.actions.splice(index, 1);
  53395. ActionManager.Triggers[action.trigger] -= 1;
  53396. if (ActionManager.Triggers[action.trigger] === 0) {
  53397. delete ActionManager.Triggers[action.trigger];
  53398. }
  53399. delete action._actionManager;
  53400. return true;
  53401. }
  53402. return false;
  53403. };
  53404. /**
  53405. * Process a specific trigger
  53406. * @param trigger defines the trigger to process
  53407. * @param evt defines the event details to be processed
  53408. */
  53409. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53410. for (var index = 0; index < this.actions.length; index++) {
  53411. var action = this.actions[index];
  53412. if (action.trigger === trigger) {
  53413. if (evt) {
  53414. if (trigger === ActionManager.OnKeyUpTrigger
  53415. || trigger === ActionManager.OnKeyDownTrigger) {
  53416. var parameter = action.getTriggerParameter();
  53417. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53418. if (!parameter.toLowerCase) {
  53419. continue;
  53420. }
  53421. var lowerCase = parameter.toLowerCase();
  53422. if (lowerCase !== evt.sourceEvent.key) {
  53423. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53424. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53425. if (actualkey !== lowerCase) {
  53426. continue;
  53427. }
  53428. }
  53429. }
  53430. }
  53431. }
  53432. action._executeCurrent(evt);
  53433. }
  53434. }
  53435. };
  53436. /** @hidden */
  53437. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53438. var properties = propertyPath.split(".");
  53439. for (var index = 0; index < properties.length - 1; index++) {
  53440. target = target[properties[index]];
  53441. }
  53442. return target;
  53443. };
  53444. /** @hidden */
  53445. ActionManager.prototype._getProperty = function (propertyPath) {
  53446. var properties = propertyPath.split(".");
  53447. return properties[properties.length - 1];
  53448. };
  53449. /**
  53450. * Serialize this manager to a JSON object
  53451. * @param name defines the property name to store this manager
  53452. * @returns a JSON representation of this manager
  53453. */
  53454. ActionManager.prototype.serialize = function (name) {
  53455. var root = {
  53456. children: new Array(),
  53457. name: name,
  53458. type: 3,
  53459. properties: new Array() // Empty for root but required
  53460. };
  53461. for (var i = 0; i < this.actions.length; i++) {
  53462. var triggerObject = {
  53463. type: 0,
  53464. children: new Array(),
  53465. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53466. properties: new Array()
  53467. };
  53468. var triggerOptions = this.actions[i].triggerOptions;
  53469. if (triggerOptions && typeof triggerOptions !== "number") {
  53470. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53471. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53472. }
  53473. else {
  53474. var parameter = {};
  53475. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53476. if (triggerOptions.parameter.mesh) {
  53477. parameter._meshId = triggerOptions.parameter.mesh.id;
  53478. }
  53479. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53480. }
  53481. }
  53482. // Serialize child action, recursively
  53483. this.actions[i].serialize(triggerObject);
  53484. // Add serialized trigger
  53485. root.children.push(triggerObject);
  53486. }
  53487. return root;
  53488. };
  53489. /**
  53490. * Creates a new ActionManager from a JSON data
  53491. * @param parsedActions defines the JSON data to read from
  53492. * @param object defines the hosting mesh
  53493. * @param scene defines the hosting scene
  53494. */
  53495. ActionManager.Parse = function (parsedActions, object, scene) {
  53496. var actionManager = new ActionManager(scene);
  53497. if (object === null)
  53498. scene.actionManager = actionManager;
  53499. else
  53500. object.actionManager = actionManager;
  53501. // instanciate a new object
  53502. var instanciate = function (name, params) {
  53503. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53504. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53505. newInstance.constructor.apply(newInstance, params);
  53506. return newInstance;
  53507. };
  53508. var parseParameter = function (name, value, target, propertyPath) {
  53509. if (propertyPath === null) {
  53510. // String, boolean or float
  53511. var floatValue = parseFloat(value);
  53512. if (value === "true" || value === "false")
  53513. return value === "true";
  53514. else
  53515. return isNaN(floatValue) ? value : floatValue;
  53516. }
  53517. var effectiveTarget = propertyPath.split(".");
  53518. var values = value.split(",");
  53519. // Get effective Target
  53520. for (var i = 0; i < effectiveTarget.length; i++) {
  53521. target = target[effectiveTarget[i]];
  53522. }
  53523. // Return appropriate value with its type
  53524. if (typeof (target) === "boolean")
  53525. return values[0] === "true";
  53526. if (typeof (target) === "string")
  53527. return values[0];
  53528. // Parameters with multiple values such as Vector3 etc.
  53529. var split = new Array();
  53530. for (var i = 0; i < values.length; i++)
  53531. split.push(parseFloat(values[i]));
  53532. if (target instanceof BABYLON.Vector3)
  53533. return BABYLON.Vector3.FromArray(split);
  53534. if (target instanceof BABYLON.Vector4)
  53535. return BABYLON.Vector4.FromArray(split);
  53536. if (target instanceof BABYLON.Color3)
  53537. return BABYLON.Color3.FromArray(split);
  53538. if (target instanceof BABYLON.Color4)
  53539. return BABYLON.Color4.FromArray(split);
  53540. return parseFloat(values[0]);
  53541. };
  53542. // traverse graph per trigger
  53543. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53544. if (combineArray === void 0) { combineArray = null; }
  53545. if (parsedAction.detached)
  53546. return;
  53547. var parameters = new Array();
  53548. var target = null;
  53549. var propertyPath = null;
  53550. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53551. // Parameters
  53552. if (parsedAction.type === 2)
  53553. parameters.push(actionManager);
  53554. else
  53555. parameters.push(trigger);
  53556. if (combine) {
  53557. var actions = new Array();
  53558. for (var j = 0; j < parsedAction.combine.length; j++) {
  53559. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53560. }
  53561. parameters.push(actions);
  53562. }
  53563. else {
  53564. for (var i = 0; i < parsedAction.properties.length; i++) {
  53565. var value = parsedAction.properties[i].value;
  53566. var name = parsedAction.properties[i].name;
  53567. var targetType = parsedAction.properties[i].targetType;
  53568. if (name === "target")
  53569. if (targetType !== null && targetType === "SceneProperties")
  53570. value = target = scene;
  53571. else
  53572. value = target = scene.getNodeByName(value);
  53573. else if (name === "parent")
  53574. value = scene.getNodeByName(value);
  53575. else if (name === "sound")
  53576. value = scene.getSoundByName(value);
  53577. else if (name !== "propertyPath") {
  53578. if (parsedAction.type === 2 && name === "operator")
  53579. value = BABYLON.ValueCondition[value];
  53580. else
  53581. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53582. }
  53583. else {
  53584. propertyPath = value;
  53585. }
  53586. parameters.push(value);
  53587. }
  53588. }
  53589. if (combineArray === null) {
  53590. parameters.push(condition);
  53591. }
  53592. else {
  53593. parameters.push(null);
  53594. }
  53595. // If interpolate value action
  53596. if (parsedAction.name === "InterpolateValueAction") {
  53597. var param = parameters[parameters.length - 2];
  53598. parameters[parameters.length - 1] = param;
  53599. parameters[parameters.length - 2] = condition;
  53600. }
  53601. // Action or condition(s) and not CombineAction
  53602. var newAction = instanciate(parsedAction.name, parameters);
  53603. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53604. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53605. if (action)
  53606. action.then(nothing);
  53607. else
  53608. actionManager.registerAction(nothing);
  53609. action = nothing;
  53610. }
  53611. if (combineArray === null) {
  53612. if (newAction instanceof BABYLON.Condition) {
  53613. condition = newAction;
  53614. newAction = action;
  53615. }
  53616. else {
  53617. condition = null;
  53618. if (action)
  53619. action.then(newAction);
  53620. else
  53621. actionManager.registerAction(newAction);
  53622. }
  53623. }
  53624. else {
  53625. combineArray.push(newAction);
  53626. }
  53627. for (var i = 0; i < parsedAction.children.length; i++)
  53628. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53629. };
  53630. // triggers
  53631. for (var i = 0; i < parsedActions.children.length; i++) {
  53632. var triggerParams;
  53633. var trigger = parsedActions.children[i];
  53634. if (trigger.properties.length > 0) {
  53635. var param = trigger.properties[0].value;
  53636. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53637. if (value._meshId) {
  53638. value.mesh = scene.getMeshByID(value._meshId);
  53639. }
  53640. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53641. }
  53642. else
  53643. triggerParams = ActionManager[trigger.name];
  53644. for (var j = 0; j < trigger.children.length; j++) {
  53645. if (!trigger.detached)
  53646. traverse(trigger.children[j], triggerParams, null, null);
  53647. }
  53648. }
  53649. };
  53650. /**
  53651. * Get a trigger name by index
  53652. * @param trigger defines the trigger index
  53653. * @returns a trigger name
  53654. */
  53655. ActionManager.GetTriggerName = function (trigger) {
  53656. switch (trigger) {
  53657. case 0: return "NothingTrigger";
  53658. case 1: return "OnPickTrigger";
  53659. case 2: return "OnLeftPickTrigger";
  53660. case 3: return "OnRightPickTrigger";
  53661. case 4: return "OnCenterPickTrigger";
  53662. case 5: return "OnPickDownTrigger";
  53663. case 6: return "OnPickUpTrigger";
  53664. case 7: return "OnLongPressTrigger";
  53665. case 8: return "OnPointerOverTrigger";
  53666. case 9: return "OnPointerOutTrigger";
  53667. case 10: return "OnEveryFrameTrigger";
  53668. case 11: return "OnIntersectionEnterTrigger";
  53669. case 12: return "OnIntersectionExitTrigger";
  53670. case 13: return "OnKeyDownTrigger";
  53671. case 14: return "OnKeyUpTrigger";
  53672. case 15: return "OnPickOutTrigger";
  53673. default: return "";
  53674. }
  53675. };
  53676. // Statics
  53677. ActionManager._NothingTrigger = 0;
  53678. ActionManager._OnPickTrigger = 1;
  53679. ActionManager._OnLeftPickTrigger = 2;
  53680. ActionManager._OnRightPickTrigger = 3;
  53681. ActionManager._OnCenterPickTrigger = 4;
  53682. ActionManager._OnPickDownTrigger = 5;
  53683. ActionManager._OnDoublePickTrigger = 6;
  53684. ActionManager._OnPickUpTrigger = 7;
  53685. ActionManager._OnLongPressTrigger = 8;
  53686. ActionManager._OnPointerOverTrigger = 9;
  53687. ActionManager._OnPointerOutTrigger = 10;
  53688. ActionManager._OnEveryFrameTrigger = 11;
  53689. ActionManager._OnIntersectionEnterTrigger = 12;
  53690. ActionManager._OnIntersectionExitTrigger = 13;
  53691. ActionManager._OnKeyDownTrigger = 14;
  53692. ActionManager._OnKeyUpTrigger = 15;
  53693. ActionManager._OnPickOutTrigger = 16;
  53694. /** Gets the list of active triggers */
  53695. ActionManager.Triggers = {};
  53696. return ActionManager;
  53697. }());
  53698. BABYLON.ActionManager = ActionManager;
  53699. })(BABYLON || (BABYLON = {}));
  53700. //# sourceMappingURL=babylon.actionManager.js.map
  53701. var BABYLON;
  53702. (function (BABYLON) {
  53703. var InterpolateValueAction = /** @class */ (function (_super) {
  53704. __extends(InterpolateValueAction, _super);
  53705. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53706. if (duration === void 0) { duration = 1000; }
  53707. var _this = _super.call(this, triggerOptions, condition) || this;
  53708. _this.propertyPath = propertyPath;
  53709. _this.value = value;
  53710. _this.duration = duration;
  53711. _this.stopOtherAnimations = stopOtherAnimations;
  53712. _this.onInterpolationDone = onInterpolationDone;
  53713. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53714. _this._target = _this._effectiveTarget = target;
  53715. return _this;
  53716. }
  53717. InterpolateValueAction.prototype._prepare = function () {
  53718. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53719. this._property = this._getProperty(this.propertyPath);
  53720. };
  53721. InterpolateValueAction.prototype.execute = function () {
  53722. var _this = this;
  53723. var scene = this._actionManager.getScene();
  53724. var keys = [
  53725. {
  53726. frame: 0,
  53727. value: this._effectiveTarget[this._property]
  53728. }, {
  53729. frame: 100,
  53730. value: this.value
  53731. }
  53732. ];
  53733. var dataType;
  53734. if (typeof this.value === "number") {
  53735. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53736. }
  53737. else if (this.value instanceof BABYLON.Color3) {
  53738. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53739. }
  53740. else if (this.value instanceof BABYLON.Vector3) {
  53741. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53742. }
  53743. else if (this.value instanceof BABYLON.Matrix) {
  53744. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53745. }
  53746. else if (this.value instanceof BABYLON.Quaternion) {
  53747. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53748. }
  53749. else {
  53750. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53751. return;
  53752. }
  53753. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53754. animation.setKeys(keys);
  53755. if (this.stopOtherAnimations) {
  53756. scene.stopAnimation(this._effectiveTarget);
  53757. }
  53758. var wrapper = function () {
  53759. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53760. if (_this.onInterpolationDone) {
  53761. _this.onInterpolationDone();
  53762. }
  53763. };
  53764. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53765. };
  53766. InterpolateValueAction.prototype.serialize = function (parent) {
  53767. return _super.prototype._serialize.call(this, {
  53768. name: "InterpolateValueAction",
  53769. properties: [
  53770. BABYLON.Action._GetTargetProperty(this._target),
  53771. { name: "propertyPath", value: this.propertyPath },
  53772. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53773. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53774. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53775. ]
  53776. }, parent);
  53777. };
  53778. return InterpolateValueAction;
  53779. }(BABYLON.Action));
  53780. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53781. })(BABYLON || (BABYLON = {}));
  53782. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53783. var BABYLON;
  53784. (function (BABYLON) {
  53785. var SwitchBooleanAction = /** @class */ (function (_super) {
  53786. __extends(SwitchBooleanAction, _super);
  53787. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53788. var _this = _super.call(this, triggerOptions, condition) || this;
  53789. _this.propertyPath = propertyPath;
  53790. _this._target = _this._effectiveTarget = target;
  53791. return _this;
  53792. }
  53793. SwitchBooleanAction.prototype._prepare = function () {
  53794. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53795. this._property = this._getProperty(this.propertyPath);
  53796. };
  53797. SwitchBooleanAction.prototype.execute = function () {
  53798. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53799. };
  53800. SwitchBooleanAction.prototype.serialize = function (parent) {
  53801. return _super.prototype._serialize.call(this, {
  53802. name: "SwitchBooleanAction",
  53803. properties: [
  53804. BABYLON.Action._GetTargetProperty(this._target),
  53805. { name: "propertyPath", value: this.propertyPath }
  53806. ]
  53807. }, parent);
  53808. };
  53809. return SwitchBooleanAction;
  53810. }(BABYLON.Action));
  53811. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53812. var SetStateAction = /** @class */ (function (_super) {
  53813. __extends(SetStateAction, _super);
  53814. function SetStateAction(triggerOptions, target, value, condition) {
  53815. var _this = _super.call(this, triggerOptions, condition) || this;
  53816. _this.value = value;
  53817. _this._target = target;
  53818. return _this;
  53819. }
  53820. SetStateAction.prototype.execute = function () {
  53821. this._target.state = this.value;
  53822. };
  53823. SetStateAction.prototype.serialize = function (parent) {
  53824. return _super.prototype._serialize.call(this, {
  53825. name: "SetStateAction",
  53826. properties: [
  53827. BABYLON.Action._GetTargetProperty(this._target),
  53828. { name: "value", value: this.value }
  53829. ]
  53830. }, parent);
  53831. };
  53832. return SetStateAction;
  53833. }(BABYLON.Action));
  53834. BABYLON.SetStateAction = SetStateAction;
  53835. var SetValueAction = /** @class */ (function (_super) {
  53836. __extends(SetValueAction, _super);
  53837. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53838. var _this = _super.call(this, triggerOptions, condition) || this;
  53839. _this.propertyPath = propertyPath;
  53840. _this.value = value;
  53841. _this._target = _this._effectiveTarget = target;
  53842. return _this;
  53843. }
  53844. SetValueAction.prototype._prepare = function () {
  53845. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53846. this._property = this._getProperty(this.propertyPath);
  53847. };
  53848. SetValueAction.prototype.execute = function () {
  53849. this._effectiveTarget[this._property] = this.value;
  53850. if (this._target.markAsDirty) {
  53851. this._target.markAsDirty(this._property);
  53852. }
  53853. };
  53854. SetValueAction.prototype.serialize = function (parent) {
  53855. return _super.prototype._serialize.call(this, {
  53856. name: "SetValueAction",
  53857. properties: [
  53858. BABYLON.Action._GetTargetProperty(this._target),
  53859. { name: "propertyPath", value: this.propertyPath },
  53860. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53861. ]
  53862. }, parent);
  53863. };
  53864. return SetValueAction;
  53865. }(BABYLON.Action));
  53866. BABYLON.SetValueAction = SetValueAction;
  53867. var IncrementValueAction = /** @class */ (function (_super) {
  53868. __extends(IncrementValueAction, _super);
  53869. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53870. var _this = _super.call(this, triggerOptions, condition) || this;
  53871. _this.propertyPath = propertyPath;
  53872. _this.value = value;
  53873. _this._target = _this._effectiveTarget = target;
  53874. return _this;
  53875. }
  53876. IncrementValueAction.prototype._prepare = function () {
  53877. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53878. this._property = this._getProperty(this.propertyPath);
  53879. if (typeof this._effectiveTarget[this._property] !== "number") {
  53880. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53881. }
  53882. };
  53883. IncrementValueAction.prototype.execute = function () {
  53884. this._effectiveTarget[this._property] += this.value;
  53885. if (this._target.markAsDirty) {
  53886. this._target.markAsDirty(this._property);
  53887. }
  53888. };
  53889. IncrementValueAction.prototype.serialize = function (parent) {
  53890. return _super.prototype._serialize.call(this, {
  53891. name: "IncrementValueAction",
  53892. properties: [
  53893. BABYLON.Action._GetTargetProperty(this._target),
  53894. { name: "propertyPath", value: this.propertyPath },
  53895. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53896. ]
  53897. }, parent);
  53898. };
  53899. return IncrementValueAction;
  53900. }(BABYLON.Action));
  53901. BABYLON.IncrementValueAction = IncrementValueAction;
  53902. var PlayAnimationAction = /** @class */ (function (_super) {
  53903. __extends(PlayAnimationAction, _super);
  53904. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53905. var _this = _super.call(this, triggerOptions, condition) || this;
  53906. _this.from = from;
  53907. _this.to = to;
  53908. _this.loop = loop;
  53909. _this._target = target;
  53910. return _this;
  53911. }
  53912. PlayAnimationAction.prototype._prepare = function () {
  53913. };
  53914. PlayAnimationAction.prototype.execute = function () {
  53915. var scene = this._actionManager.getScene();
  53916. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53917. };
  53918. PlayAnimationAction.prototype.serialize = function (parent) {
  53919. return _super.prototype._serialize.call(this, {
  53920. name: "PlayAnimationAction",
  53921. properties: [
  53922. BABYLON.Action._GetTargetProperty(this._target),
  53923. { name: "from", value: String(this.from) },
  53924. { name: "to", value: String(this.to) },
  53925. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53926. ]
  53927. }, parent);
  53928. };
  53929. return PlayAnimationAction;
  53930. }(BABYLON.Action));
  53931. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53932. var StopAnimationAction = /** @class */ (function (_super) {
  53933. __extends(StopAnimationAction, _super);
  53934. function StopAnimationAction(triggerOptions, target, condition) {
  53935. var _this = _super.call(this, triggerOptions, condition) || this;
  53936. _this._target = target;
  53937. return _this;
  53938. }
  53939. StopAnimationAction.prototype._prepare = function () {
  53940. };
  53941. StopAnimationAction.prototype.execute = function () {
  53942. var scene = this._actionManager.getScene();
  53943. scene.stopAnimation(this._target);
  53944. };
  53945. StopAnimationAction.prototype.serialize = function (parent) {
  53946. return _super.prototype._serialize.call(this, {
  53947. name: "StopAnimationAction",
  53948. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53949. }, parent);
  53950. };
  53951. return StopAnimationAction;
  53952. }(BABYLON.Action));
  53953. BABYLON.StopAnimationAction = StopAnimationAction;
  53954. var DoNothingAction = /** @class */ (function (_super) {
  53955. __extends(DoNothingAction, _super);
  53956. function DoNothingAction(triggerOptions, condition) {
  53957. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53958. return _super.call(this, triggerOptions, condition) || this;
  53959. }
  53960. DoNothingAction.prototype.execute = function () {
  53961. };
  53962. DoNothingAction.prototype.serialize = function (parent) {
  53963. return _super.prototype._serialize.call(this, {
  53964. name: "DoNothingAction",
  53965. properties: []
  53966. }, parent);
  53967. };
  53968. return DoNothingAction;
  53969. }(BABYLON.Action));
  53970. BABYLON.DoNothingAction = DoNothingAction;
  53971. var CombineAction = /** @class */ (function (_super) {
  53972. __extends(CombineAction, _super);
  53973. function CombineAction(triggerOptions, children, condition) {
  53974. var _this = _super.call(this, triggerOptions, condition) || this;
  53975. _this.children = children;
  53976. return _this;
  53977. }
  53978. CombineAction.prototype._prepare = function () {
  53979. for (var index = 0; index < this.children.length; index++) {
  53980. this.children[index]._actionManager = this._actionManager;
  53981. this.children[index]._prepare();
  53982. }
  53983. };
  53984. CombineAction.prototype.execute = function (evt) {
  53985. for (var index = 0; index < this.children.length; index++) {
  53986. this.children[index].execute(evt);
  53987. }
  53988. };
  53989. CombineAction.prototype.serialize = function (parent) {
  53990. var serializationObject = _super.prototype._serialize.call(this, {
  53991. name: "CombineAction",
  53992. properties: [],
  53993. combine: []
  53994. }, parent);
  53995. for (var i = 0; i < this.children.length; i++) {
  53996. serializationObject.combine.push(this.children[i].serialize(null));
  53997. }
  53998. return serializationObject;
  53999. };
  54000. return CombineAction;
  54001. }(BABYLON.Action));
  54002. BABYLON.CombineAction = CombineAction;
  54003. var ExecuteCodeAction = /** @class */ (function (_super) {
  54004. __extends(ExecuteCodeAction, _super);
  54005. function ExecuteCodeAction(triggerOptions, func, condition) {
  54006. var _this = _super.call(this, triggerOptions, condition) || this;
  54007. _this.func = func;
  54008. return _this;
  54009. }
  54010. ExecuteCodeAction.prototype.execute = function (evt) {
  54011. this.func(evt);
  54012. };
  54013. return ExecuteCodeAction;
  54014. }(BABYLON.Action));
  54015. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54016. var SetParentAction = /** @class */ (function (_super) {
  54017. __extends(SetParentAction, _super);
  54018. function SetParentAction(triggerOptions, target, parent, condition) {
  54019. var _this = _super.call(this, triggerOptions, condition) || this;
  54020. _this._target = target;
  54021. _this._parent = parent;
  54022. return _this;
  54023. }
  54024. SetParentAction.prototype._prepare = function () {
  54025. };
  54026. SetParentAction.prototype.execute = function () {
  54027. if (this._target.parent === this._parent) {
  54028. return;
  54029. }
  54030. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54031. invertParentWorldMatrix.invert();
  54032. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54033. this._target.parent = this._parent;
  54034. };
  54035. SetParentAction.prototype.serialize = function (parent) {
  54036. return _super.prototype._serialize.call(this, {
  54037. name: "SetParentAction",
  54038. properties: [
  54039. BABYLON.Action._GetTargetProperty(this._target),
  54040. BABYLON.Action._GetTargetProperty(this._parent),
  54041. ]
  54042. }, parent);
  54043. };
  54044. return SetParentAction;
  54045. }(BABYLON.Action));
  54046. BABYLON.SetParentAction = SetParentAction;
  54047. var PlaySoundAction = /** @class */ (function (_super) {
  54048. __extends(PlaySoundAction, _super);
  54049. function PlaySoundAction(triggerOptions, sound, condition) {
  54050. var _this = _super.call(this, triggerOptions, condition) || this;
  54051. _this._sound = sound;
  54052. return _this;
  54053. }
  54054. PlaySoundAction.prototype._prepare = function () {
  54055. };
  54056. PlaySoundAction.prototype.execute = function () {
  54057. if (this._sound !== undefined)
  54058. this._sound.play();
  54059. };
  54060. PlaySoundAction.prototype.serialize = function (parent) {
  54061. return _super.prototype._serialize.call(this, {
  54062. name: "PlaySoundAction",
  54063. properties: [{ name: "sound", value: this._sound.name }]
  54064. }, parent);
  54065. };
  54066. return PlaySoundAction;
  54067. }(BABYLON.Action));
  54068. BABYLON.PlaySoundAction = PlaySoundAction;
  54069. var StopSoundAction = /** @class */ (function (_super) {
  54070. __extends(StopSoundAction, _super);
  54071. function StopSoundAction(triggerOptions, sound, condition) {
  54072. var _this = _super.call(this, triggerOptions, condition) || this;
  54073. _this._sound = sound;
  54074. return _this;
  54075. }
  54076. StopSoundAction.prototype._prepare = function () {
  54077. };
  54078. StopSoundAction.prototype.execute = function () {
  54079. if (this._sound !== undefined)
  54080. this._sound.stop();
  54081. };
  54082. StopSoundAction.prototype.serialize = function (parent) {
  54083. return _super.prototype._serialize.call(this, {
  54084. name: "StopSoundAction",
  54085. properties: [{ name: "sound", value: this._sound.name }]
  54086. }, parent);
  54087. };
  54088. return StopSoundAction;
  54089. }(BABYLON.Action));
  54090. BABYLON.StopSoundAction = StopSoundAction;
  54091. })(BABYLON || (BABYLON = {}));
  54092. //# sourceMappingURL=babylon.directActions.js.map
  54093. var BABYLON;
  54094. (function (BABYLON) {
  54095. var SpriteManager = /** @class */ (function () {
  54096. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54097. if (epsilon === void 0) { epsilon = 0.01; }
  54098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54099. this.name = name;
  54100. this.sprites = new Array();
  54101. this.renderingGroupId = 0;
  54102. this.layerMask = 0x0FFFFFFF;
  54103. this.fogEnabled = true;
  54104. this.isPickable = false;
  54105. /**
  54106. * An event triggered when the manager is disposed.
  54107. */
  54108. this.onDisposeObservable = new BABYLON.Observable();
  54109. this._vertexBuffers = {};
  54110. this._capacity = capacity;
  54111. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54112. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54113. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54114. if (cellSize.width && cellSize.height) {
  54115. this.cellWidth = cellSize.width;
  54116. this.cellHeight = cellSize.height;
  54117. }
  54118. else if (cellSize !== undefined) {
  54119. this.cellWidth = cellSize;
  54120. this.cellHeight = cellSize;
  54121. }
  54122. else {
  54123. return;
  54124. }
  54125. this._epsilon = epsilon;
  54126. this._scene = scene;
  54127. this._scene.spriteManagers.push(this);
  54128. var indices = [];
  54129. var index = 0;
  54130. for (var count = 0; count < capacity; count++) {
  54131. indices.push(index);
  54132. indices.push(index + 1);
  54133. indices.push(index + 2);
  54134. indices.push(index);
  54135. indices.push(index + 2);
  54136. indices.push(index + 3);
  54137. index += 4;
  54138. }
  54139. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54140. // VBO
  54141. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54142. this._vertexData = new Float32Array(capacity * 16 * 4);
  54143. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54144. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54145. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54146. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54147. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54148. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54149. this._vertexBuffers["options"] = options;
  54150. this._vertexBuffers["cellInfo"] = cellInfo;
  54151. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54152. // Effects
  54153. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54154. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54155. }
  54156. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54157. set: function (callback) {
  54158. if (this._onDisposeObserver) {
  54159. this.onDisposeObservable.remove(this._onDisposeObserver);
  54160. }
  54161. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54162. },
  54163. enumerable: true,
  54164. configurable: true
  54165. });
  54166. Object.defineProperty(SpriteManager.prototype, "texture", {
  54167. get: function () {
  54168. return this._spriteTexture;
  54169. },
  54170. set: function (value) {
  54171. this._spriteTexture = value;
  54172. },
  54173. enumerable: true,
  54174. configurable: true
  54175. });
  54176. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54177. var arrayOffset = index * 16;
  54178. if (offsetX === 0)
  54179. offsetX = this._epsilon;
  54180. else if (offsetX === 1)
  54181. offsetX = 1 - this._epsilon;
  54182. if (offsetY === 0)
  54183. offsetY = this._epsilon;
  54184. else if (offsetY === 1)
  54185. offsetY = 1 - this._epsilon;
  54186. this._vertexData[arrayOffset] = sprite.position.x;
  54187. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54188. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54189. this._vertexData[arrayOffset + 3] = sprite.angle;
  54190. this._vertexData[arrayOffset + 4] = sprite.width;
  54191. this._vertexData[arrayOffset + 5] = sprite.height;
  54192. this._vertexData[arrayOffset + 6] = offsetX;
  54193. this._vertexData[arrayOffset + 7] = offsetY;
  54194. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54195. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54196. var offset = (sprite.cellIndex / rowSize) >> 0;
  54197. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54198. this._vertexData[arrayOffset + 11] = offset;
  54199. // Color
  54200. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54201. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54202. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54203. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54204. };
  54205. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54206. var count = Math.min(this._capacity, this.sprites.length);
  54207. var min = BABYLON.Vector3.Zero();
  54208. var max = BABYLON.Vector3.Zero();
  54209. var distance = Number.MAX_VALUE;
  54210. var currentSprite = null;
  54211. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54212. var cameraView = camera.getViewMatrix();
  54213. for (var index = 0; index < count; index++) {
  54214. var sprite = this.sprites[index];
  54215. if (!sprite) {
  54216. continue;
  54217. }
  54218. if (predicate) {
  54219. if (!predicate(sprite)) {
  54220. continue;
  54221. }
  54222. }
  54223. else if (!sprite.isPickable) {
  54224. continue;
  54225. }
  54226. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54227. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54228. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54229. if (ray.intersectsBoxMinMax(min, max)) {
  54230. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54231. if (distance > currentDistance) {
  54232. distance = currentDistance;
  54233. currentSprite = sprite;
  54234. if (fastCheck) {
  54235. break;
  54236. }
  54237. }
  54238. }
  54239. }
  54240. if (currentSprite) {
  54241. var result = new BABYLON.PickingInfo();
  54242. result.hit = true;
  54243. result.pickedSprite = currentSprite;
  54244. result.distance = distance;
  54245. return result;
  54246. }
  54247. return null;
  54248. };
  54249. SpriteManager.prototype.render = function () {
  54250. // Check
  54251. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54252. return;
  54253. var engine = this._scene.getEngine();
  54254. var baseSize = this._spriteTexture.getBaseSize();
  54255. // Sprites
  54256. var deltaTime = engine.getDeltaTime();
  54257. var max = Math.min(this._capacity, this.sprites.length);
  54258. var rowSize = baseSize.width / this.cellWidth;
  54259. var offset = 0;
  54260. for (var index = 0; index < max; index++) {
  54261. var sprite = this.sprites[index];
  54262. if (!sprite) {
  54263. continue;
  54264. }
  54265. sprite._animate(deltaTime);
  54266. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54267. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54268. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54269. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54270. }
  54271. this._buffer.update(this._vertexData);
  54272. // Render
  54273. var effect = this._effectBase;
  54274. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54275. effect = this._effectFog;
  54276. }
  54277. engine.enableEffect(effect);
  54278. var viewMatrix = this._scene.getViewMatrix();
  54279. effect.setTexture("diffuseSampler", this._spriteTexture);
  54280. effect.setMatrix("view", viewMatrix);
  54281. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54282. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54283. // Fog
  54284. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54285. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54286. effect.setColor3("vFogColor", this._scene.fogColor);
  54287. }
  54288. // VBOs
  54289. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54290. // Draw order
  54291. engine.setDepthFunctionToLessOrEqual();
  54292. effect.setBool("alphaTest", true);
  54293. engine.setColorWrite(false);
  54294. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54295. engine.setColorWrite(true);
  54296. effect.setBool("alphaTest", false);
  54297. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54298. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54299. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54300. };
  54301. SpriteManager.prototype.dispose = function () {
  54302. if (this._buffer) {
  54303. this._buffer.dispose();
  54304. this._buffer = null;
  54305. }
  54306. if (this._indexBuffer) {
  54307. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54308. this._indexBuffer = null;
  54309. }
  54310. if (this._spriteTexture) {
  54311. this._spriteTexture.dispose();
  54312. this._spriteTexture = null;
  54313. }
  54314. // Remove from scene
  54315. var index = this._scene.spriteManagers.indexOf(this);
  54316. this._scene.spriteManagers.splice(index, 1);
  54317. // Callback
  54318. this.onDisposeObservable.notifyObservers(this);
  54319. this.onDisposeObservable.clear();
  54320. };
  54321. return SpriteManager;
  54322. }());
  54323. BABYLON.SpriteManager = SpriteManager;
  54324. })(BABYLON || (BABYLON = {}));
  54325. //# sourceMappingURL=babylon.spriteManager.js.map
  54326. var BABYLON;
  54327. (function (BABYLON) {
  54328. var Sprite = /** @class */ (function () {
  54329. function Sprite(name, manager) {
  54330. this.name = name;
  54331. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54332. this.width = 1.0;
  54333. this.height = 1.0;
  54334. this.angle = 0;
  54335. this.cellIndex = 0;
  54336. this.invertU = 0;
  54337. this.invertV = 0;
  54338. this.animations = new Array();
  54339. this.isPickable = false;
  54340. this._animationStarted = false;
  54341. this._loopAnimation = false;
  54342. this._fromIndex = 0;
  54343. this._toIndex = 0;
  54344. this._delay = 0;
  54345. this._direction = 1;
  54346. this._time = 0;
  54347. this._manager = manager;
  54348. this._manager.sprites.push(this);
  54349. this.position = BABYLON.Vector3.Zero();
  54350. }
  54351. Object.defineProperty(Sprite.prototype, "size", {
  54352. get: function () {
  54353. return this.width;
  54354. },
  54355. set: function (value) {
  54356. this.width = value;
  54357. this.height = value;
  54358. },
  54359. enumerable: true,
  54360. configurable: true
  54361. });
  54362. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54363. this._fromIndex = from;
  54364. this._toIndex = to;
  54365. this._loopAnimation = loop;
  54366. this._delay = delay;
  54367. this._animationStarted = true;
  54368. this._direction = from < to ? 1 : -1;
  54369. this.cellIndex = from;
  54370. this._time = 0;
  54371. this._onAnimationEnd = onAnimationEnd;
  54372. };
  54373. Sprite.prototype.stopAnimation = function () {
  54374. this._animationStarted = false;
  54375. };
  54376. Sprite.prototype._animate = function (deltaTime) {
  54377. if (!this._animationStarted)
  54378. return;
  54379. this._time += deltaTime;
  54380. if (this._time > this._delay) {
  54381. this._time = this._time % this._delay;
  54382. this.cellIndex += this._direction;
  54383. if (this.cellIndex > this._toIndex) {
  54384. if (this._loopAnimation) {
  54385. this.cellIndex = this._fromIndex;
  54386. }
  54387. else {
  54388. this.cellIndex = this._toIndex;
  54389. this._animationStarted = false;
  54390. if (this._onAnimationEnd) {
  54391. this._onAnimationEnd();
  54392. }
  54393. if (this.disposeWhenFinishedAnimating) {
  54394. this.dispose();
  54395. }
  54396. }
  54397. }
  54398. }
  54399. };
  54400. Sprite.prototype.dispose = function () {
  54401. for (var i = 0; i < this._manager.sprites.length; i++) {
  54402. if (this._manager.sprites[i] == this) {
  54403. this._manager.sprites.splice(i, 1);
  54404. }
  54405. }
  54406. };
  54407. return Sprite;
  54408. }());
  54409. BABYLON.Sprite = Sprite;
  54410. })(BABYLON || (BABYLON = {}));
  54411. //# sourceMappingURL=babylon.sprite.js.map
  54412. var BABYLON;
  54413. (function (BABYLON) {
  54414. var IntersectionInfo = /** @class */ (function () {
  54415. function IntersectionInfo(bu, bv, distance) {
  54416. this.bu = bu;
  54417. this.bv = bv;
  54418. this.distance = distance;
  54419. this.faceId = 0;
  54420. this.subMeshId = 0;
  54421. }
  54422. return IntersectionInfo;
  54423. }());
  54424. BABYLON.IntersectionInfo = IntersectionInfo;
  54425. var PickingInfo = /** @class */ (function () {
  54426. function PickingInfo() {
  54427. this.hit = false;
  54428. this.distance = 0;
  54429. this.pickedPoint = null;
  54430. this.pickedMesh = null;
  54431. this.bu = 0;
  54432. this.bv = 0;
  54433. this.faceId = -1;
  54434. this.subMeshId = 0;
  54435. this.pickedSprite = null;
  54436. }
  54437. // Methods
  54438. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54439. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54440. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54441. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54442. return null;
  54443. }
  54444. var indices = this.pickedMesh.getIndices();
  54445. if (!indices) {
  54446. return null;
  54447. }
  54448. var result;
  54449. if (useVerticesNormals) {
  54450. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54451. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54452. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54453. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54454. normal0 = normal0.scale(this.bu);
  54455. normal1 = normal1.scale(this.bv);
  54456. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54457. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54458. }
  54459. else {
  54460. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54461. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54462. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54463. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54464. var p1p2 = vertex1.subtract(vertex2);
  54465. var p3p2 = vertex3.subtract(vertex2);
  54466. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54467. }
  54468. if (useWorldCoordinates) {
  54469. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54470. }
  54471. return BABYLON.Vector3.Normalize(result);
  54472. };
  54473. PickingInfo.prototype.getTextureCoordinates = function () {
  54474. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54475. return null;
  54476. }
  54477. var indices = this.pickedMesh.getIndices();
  54478. if (!indices) {
  54479. return null;
  54480. }
  54481. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54482. if (!uvs) {
  54483. return null;
  54484. }
  54485. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54486. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54487. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54488. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54489. uv1 = uv1.scale(this.bu);
  54490. uv2 = uv2.scale(this.bv);
  54491. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54492. };
  54493. return PickingInfo;
  54494. }());
  54495. BABYLON.PickingInfo = PickingInfo;
  54496. })(BABYLON || (BABYLON = {}));
  54497. //# sourceMappingURL=babylon.pickingInfo.js.map
  54498. var BABYLON;
  54499. (function (BABYLON) {
  54500. var Ray = /** @class */ (function () {
  54501. function Ray(origin, direction, length) {
  54502. if (length === void 0) { length = Number.MAX_VALUE; }
  54503. this.origin = origin;
  54504. this.direction = direction;
  54505. this.length = length;
  54506. }
  54507. // Methods
  54508. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54509. var d = 0.0;
  54510. var maxValue = Number.MAX_VALUE;
  54511. var inv;
  54512. var min;
  54513. var max;
  54514. var temp;
  54515. if (Math.abs(this.direction.x) < 0.0000001) {
  54516. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54517. return false;
  54518. }
  54519. }
  54520. else {
  54521. inv = 1.0 / this.direction.x;
  54522. min = (minimum.x - this.origin.x) * inv;
  54523. max = (maximum.x - this.origin.x) * inv;
  54524. if (max === -Infinity) {
  54525. max = Infinity;
  54526. }
  54527. if (min > max) {
  54528. temp = min;
  54529. min = max;
  54530. max = temp;
  54531. }
  54532. d = Math.max(min, d);
  54533. maxValue = Math.min(max, maxValue);
  54534. if (d > maxValue) {
  54535. return false;
  54536. }
  54537. }
  54538. if (Math.abs(this.direction.y) < 0.0000001) {
  54539. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54540. return false;
  54541. }
  54542. }
  54543. else {
  54544. inv = 1.0 / this.direction.y;
  54545. min = (minimum.y - this.origin.y) * inv;
  54546. max = (maximum.y - this.origin.y) * inv;
  54547. if (max === -Infinity) {
  54548. max = Infinity;
  54549. }
  54550. if (min > max) {
  54551. temp = min;
  54552. min = max;
  54553. max = temp;
  54554. }
  54555. d = Math.max(min, d);
  54556. maxValue = Math.min(max, maxValue);
  54557. if (d > maxValue) {
  54558. return false;
  54559. }
  54560. }
  54561. if (Math.abs(this.direction.z) < 0.0000001) {
  54562. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54563. return false;
  54564. }
  54565. }
  54566. else {
  54567. inv = 1.0 / this.direction.z;
  54568. min = (minimum.z - this.origin.z) * inv;
  54569. max = (maximum.z - this.origin.z) * inv;
  54570. if (max === -Infinity) {
  54571. max = Infinity;
  54572. }
  54573. if (min > max) {
  54574. temp = min;
  54575. min = max;
  54576. max = temp;
  54577. }
  54578. d = Math.max(min, d);
  54579. maxValue = Math.min(max, maxValue);
  54580. if (d > maxValue) {
  54581. return false;
  54582. }
  54583. }
  54584. return true;
  54585. };
  54586. Ray.prototype.intersectsBox = function (box) {
  54587. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54588. };
  54589. Ray.prototype.intersectsSphere = function (sphere) {
  54590. var x = sphere.center.x - this.origin.x;
  54591. var y = sphere.center.y - this.origin.y;
  54592. var z = sphere.center.z - this.origin.z;
  54593. var pyth = (x * x) + (y * y) + (z * z);
  54594. var rr = sphere.radius * sphere.radius;
  54595. if (pyth <= rr) {
  54596. return true;
  54597. }
  54598. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54599. if (dot < 0.0) {
  54600. return false;
  54601. }
  54602. var temp = pyth - (dot * dot);
  54603. return temp <= rr;
  54604. };
  54605. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54606. if (!this._edge1) {
  54607. this._edge1 = BABYLON.Vector3.Zero();
  54608. this._edge2 = BABYLON.Vector3.Zero();
  54609. this._pvec = BABYLON.Vector3.Zero();
  54610. this._tvec = BABYLON.Vector3.Zero();
  54611. this._qvec = BABYLON.Vector3.Zero();
  54612. }
  54613. vertex1.subtractToRef(vertex0, this._edge1);
  54614. vertex2.subtractToRef(vertex0, this._edge2);
  54615. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54616. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54617. if (det === 0) {
  54618. return null;
  54619. }
  54620. var invdet = 1 / det;
  54621. this.origin.subtractToRef(vertex0, this._tvec);
  54622. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54623. if (bu < 0 || bu > 1.0) {
  54624. return null;
  54625. }
  54626. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54627. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54628. if (bv < 0 || bu + bv > 1.0) {
  54629. return null;
  54630. }
  54631. //check if the distance is longer than the predefined length.
  54632. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54633. if (distance > this.length) {
  54634. return null;
  54635. }
  54636. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54637. };
  54638. Ray.prototype.intersectsPlane = function (plane) {
  54639. var distance;
  54640. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54641. if (Math.abs(result1) < 9.99999997475243E-07) {
  54642. return null;
  54643. }
  54644. else {
  54645. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54646. distance = (-plane.d - result2) / result1;
  54647. if (distance < 0.0) {
  54648. if (distance < -9.99999997475243E-07) {
  54649. return null;
  54650. }
  54651. else {
  54652. return 0;
  54653. }
  54654. }
  54655. return distance;
  54656. }
  54657. };
  54658. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54659. var tm = BABYLON.Tmp.Matrix[0];
  54660. mesh.getWorldMatrix().invertToRef(tm);
  54661. if (this._tmpRay) {
  54662. Ray.TransformToRef(this, tm, this._tmpRay);
  54663. }
  54664. else {
  54665. this._tmpRay = Ray.Transform(this, tm);
  54666. }
  54667. return mesh.intersects(this._tmpRay, fastCheck);
  54668. };
  54669. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54670. if (results) {
  54671. results.length = 0;
  54672. }
  54673. else {
  54674. results = [];
  54675. }
  54676. for (var i = 0; i < meshes.length; i++) {
  54677. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54678. if (pickInfo.hit) {
  54679. results.push(pickInfo);
  54680. }
  54681. }
  54682. results.sort(this._comparePickingInfo);
  54683. return results;
  54684. };
  54685. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54686. if (pickingInfoA.distance < pickingInfoB.distance) {
  54687. return -1;
  54688. }
  54689. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54690. return 1;
  54691. }
  54692. else {
  54693. return 0;
  54694. }
  54695. };
  54696. /**
  54697. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54698. * @param sega the first point of the segment to test the intersection against
  54699. * @param segb the second point of the segment to test the intersection against
  54700. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54701. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54702. */
  54703. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54704. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54705. var u = segb.subtract(sega);
  54706. var v = rsegb.subtract(this.origin);
  54707. var w = sega.subtract(this.origin);
  54708. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54709. var b = BABYLON.Vector3.Dot(u, v);
  54710. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54711. var d = BABYLON.Vector3.Dot(u, w);
  54712. var e = BABYLON.Vector3.Dot(v, w);
  54713. var D = a * c - b * b; // always >= 0
  54714. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54715. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54716. // compute the line parameters of the two closest points
  54717. if (D < Ray.smallnum) { // the lines are almost parallel
  54718. sN = 0.0; // force using point P0 on segment S1
  54719. sD = 1.0; // to prevent possible division by 0.0 later
  54720. tN = e;
  54721. tD = c;
  54722. }
  54723. else { // get the closest points on the infinite lines
  54724. sN = (b * e - c * d);
  54725. tN = (a * e - b * d);
  54726. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54727. sN = 0.0;
  54728. tN = e;
  54729. tD = c;
  54730. }
  54731. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54732. sN = sD;
  54733. tN = e + b;
  54734. tD = c;
  54735. }
  54736. }
  54737. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54738. tN = 0.0;
  54739. // recompute sc for this edge
  54740. if (-d < 0.0) {
  54741. sN = 0.0;
  54742. }
  54743. else if (-d > a)
  54744. sN = sD;
  54745. else {
  54746. sN = -d;
  54747. sD = a;
  54748. }
  54749. }
  54750. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54751. tN = tD;
  54752. // recompute sc for this edge
  54753. if ((-d + b) < 0.0) {
  54754. sN = 0;
  54755. }
  54756. else if ((-d + b) > a) {
  54757. sN = sD;
  54758. }
  54759. else {
  54760. sN = (-d + b);
  54761. sD = a;
  54762. }
  54763. }
  54764. // finally do the division to get sc and tc
  54765. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54766. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54767. // get the difference of the two closest points
  54768. var qtc = v.multiplyByFloats(tc, tc, tc);
  54769. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54770. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54771. if (isIntersected) {
  54772. return qtc.length();
  54773. }
  54774. return -1;
  54775. };
  54776. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54777. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54778. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54779. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54780. this.direction.normalize();
  54781. return this;
  54782. };
  54783. // Statics
  54784. Ray.Zero = function () {
  54785. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54786. };
  54787. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54788. var result = Ray.Zero();
  54789. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54790. };
  54791. /**
  54792. * 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
  54793. * transformed to the given world matrix.
  54794. * @param origin The origin point
  54795. * @param end The end point
  54796. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54797. */
  54798. Ray.CreateNewFromTo = function (origin, end, world) {
  54799. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54800. var direction = end.subtract(origin);
  54801. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54802. direction.normalize();
  54803. return Ray.Transform(new Ray(origin, direction, length), world);
  54804. };
  54805. Ray.Transform = function (ray, matrix) {
  54806. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54807. Ray.TransformToRef(ray, matrix, result);
  54808. return result;
  54809. };
  54810. Ray.TransformToRef = function (ray, matrix, result) {
  54811. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54812. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54813. result.length = ray.length;
  54814. var dir = result.direction;
  54815. var len = dir.length();
  54816. if (!(len === 0 || len === 1)) {
  54817. var num = 1.0 / len;
  54818. dir.x *= num;
  54819. dir.y *= num;
  54820. dir.z *= num;
  54821. result.length *= len;
  54822. }
  54823. };
  54824. Ray.smallnum = 0.00000001;
  54825. Ray.rayl = 10e8;
  54826. return Ray;
  54827. }());
  54828. BABYLON.Ray = Ray;
  54829. })(BABYLON || (BABYLON = {}));
  54830. //# sourceMappingURL=babylon.ray.js.map
  54831. var BABYLON;
  54832. (function (BABYLON) {
  54833. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54834. if (boxMin.x > sphereCenter.x + sphereRadius)
  54835. return false;
  54836. if (sphereCenter.x - sphereRadius > boxMax.x)
  54837. return false;
  54838. if (boxMin.y > sphereCenter.y + sphereRadius)
  54839. return false;
  54840. if (sphereCenter.y - sphereRadius > boxMax.y)
  54841. return false;
  54842. if (boxMin.z > sphereCenter.z + sphereRadius)
  54843. return false;
  54844. if (sphereCenter.z - sphereRadius > boxMax.z)
  54845. return false;
  54846. return true;
  54847. };
  54848. var getLowestRoot = (function () {
  54849. var result = { root: 0, found: false };
  54850. return function (a, b, c, maxR) {
  54851. result.root = 0;
  54852. result.found = false;
  54853. var determinant = b * b - 4.0 * a * c;
  54854. if (determinant < 0)
  54855. return result;
  54856. var sqrtD = Math.sqrt(determinant);
  54857. var r1 = (-b - sqrtD) / (2.0 * a);
  54858. var r2 = (-b + sqrtD) / (2.0 * a);
  54859. if (r1 > r2) {
  54860. var temp = r2;
  54861. r2 = r1;
  54862. r1 = temp;
  54863. }
  54864. if (r1 > 0 && r1 < maxR) {
  54865. result.root = r1;
  54866. result.found = true;
  54867. return result;
  54868. }
  54869. if (r2 > 0 && r2 < maxR) {
  54870. result.root = r2;
  54871. result.found = true;
  54872. return result;
  54873. }
  54874. return result;
  54875. };
  54876. })();
  54877. var Collider = /** @class */ (function () {
  54878. function Collider() {
  54879. this._collisionPoint = BABYLON.Vector3.Zero();
  54880. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54881. this._tempVector = BABYLON.Vector3.Zero();
  54882. this._tempVector2 = BABYLON.Vector3.Zero();
  54883. this._tempVector3 = BABYLON.Vector3.Zero();
  54884. this._tempVector4 = BABYLON.Vector3.Zero();
  54885. this._edge = BABYLON.Vector3.Zero();
  54886. this._baseToVertex = BABYLON.Vector3.Zero();
  54887. this._destinationPoint = BABYLON.Vector3.Zero();
  54888. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54889. this._displacementVector = BABYLON.Vector3.Zero();
  54890. this._radius = BABYLON.Vector3.One();
  54891. this._retry = 0;
  54892. this._basePointWorld = BABYLON.Vector3.Zero();
  54893. this._velocityWorld = BABYLON.Vector3.Zero();
  54894. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54895. this._collisionMask = -1;
  54896. }
  54897. Object.defineProperty(Collider.prototype, "collisionMask", {
  54898. get: function () {
  54899. return this._collisionMask;
  54900. },
  54901. set: function (mask) {
  54902. this._collisionMask = !isNaN(mask) ? mask : -1;
  54903. },
  54904. enumerable: true,
  54905. configurable: true
  54906. });
  54907. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54908. /**
  54909. * Gets the plane normal used to compute the sliding response (in local space)
  54910. */
  54911. get: function () {
  54912. return this._slidePlaneNormal;
  54913. },
  54914. enumerable: true,
  54915. configurable: true
  54916. });
  54917. // Methods
  54918. Collider.prototype._initialize = function (source, dir, e) {
  54919. this._velocity = dir;
  54920. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54921. this._basePoint = source;
  54922. source.multiplyToRef(this._radius, this._basePointWorld);
  54923. dir.multiplyToRef(this._radius, this._velocityWorld);
  54924. this._velocityWorldLength = this._velocityWorld.length();
  54925. this._epsilon = e;
  54926. this.collisionFound = false;
  54927. };
  54928. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54929. pa.subtractToRef(point, this._tempVector);
  54930. pb.subtractToRef(point, this._tempVector2);
  54931. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54932. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54933. if (d < 0)
  54934. return false;
  54935. pc.subtractToRef(point, this._tempVector3);
  54936. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54937. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54938. if (d < 0)
  54939. return false;
  54940. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54941. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54942. return d >= 0;
  54943. };
  54944. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54945. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54946. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54947. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54948. return false;
  54949. }
  54950. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54951. return false;
  54952. return true;
  54953. };
  54954. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54955. var t0;
  54956. var embeddedInPlane = false;
  54957. //defensive programming, actually not needed.
  54958. if (!trianglePlaneArray) {
  54959. trianglePlaneArray = [];
  54960. }
  54961. if (!trianglePlaneArray[faceIndex]) {
  54962. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54963. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54964. }
  54965. var trianglePlane = trianglePlaneArray[faceIndex];
  54966. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54967. return;
  54968. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54969. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54970. if (normalDotVelocity == 0) {
  54971. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54972. return;
  54973. embeddedInPlane = true;
  54974. t0 = 0;
  54975. }
  54976. else {
  54977. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54978. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54979. if (t0 > t1) {
  54980. var temp = t1;
  54981. t1 = t0;
  54982. t0 = temp;
  54983. }
  54984. if (t0 > 1.0 || t1 < 0.0)
  54985. return;
  54986. if (t0 < 0)
  54987. t0 = 0;
  54988. if (t0 > 1.0)
  54989. t0 = 1.0;
  54990. }
  54991. this._collisionPoint.copyFromFloats(0, 0, 0);
  54992. var found = false;
  54993. var t = 1.0;
  54994. if (!embeddedInPlane) {
  54995. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54996. this._velocity.scaleToRef(t0, this._tempVector);
  54997. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54998. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54999. found = true;
  55000. t = t0;
  55001. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55002. }
  55003. }
  55004. if (!found) {
  55005. var velocitySquaredLength = this._velocity.lengthSquared();
  55006. var a = velocitySquaredLength;
  55007. this._basePoint.subtractToRef(p1, this._tempVector);
  55008. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55009. var c = this._tempVector.lengthSquared() - 1.0;
  55010. var lowestRoot = getLowestRoot(a, b, c, t);
  55011. if (lowestRoot.found) {
  55012. t = lowestRoot.root;
  55013. found = true;
  55014. this._collisionPoint.copyFrom(p1);
  55015. }
  55016. this._basePoint.subtractToRef(p2, this._tempVector);
  55017. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55018. c = this._tempVector.lengthSquared() - 1.0;
  55019. lowestRoot = getLowestRoot(a, b, c, t);
  55020. if (lowestRoot.found) {
  55021. t = lowestRoot.root;
  55022. found = true;
  55023. this._collisionPoint.copyFrom(p2);
  55024. }
  55025. this._basePoint.subtractToRef(p3, this._tempVector);
  55026. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55027. c = this._tempVector.lengthSquared() - 1.0;
  55028. lowestRoot = getLowestRoot(a, b, c, t);
  55029. if (lowestRoot.found) {
  55030. t = lowestRoot.root;
  55031. found = true;
  55032. this._collisionPoint.copyFrom(p3);
  55033. }
  55034. p2.subtractToRef(p1, this._edge);
  55035. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55036. var edgeSquaredLength = this._edge.lengthSquared();
  55037. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55038. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55039. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55040. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55041. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55042. lowestRoot = getLowestRoot(a, b, c, t);
  55043. if (lowestRoot.found) {
  55044. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55045. if (f >= 0.0 && f <= 1.0) {
  55046. t = lowestRoot.root;
  55047. found = true;
  55048. this._edge.scaleInPlace(f);
  55049. p1.addToRef(this._edge, this._collisionPoint);
  55050. }
  55051. }
  55052. p3.subtractToRef(p2, this._edge);
  55053. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55054. edgeSquaredLength = this._edge.lengthSquared();
  55055. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55056. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55057. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55058. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55059. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55060. lowestRoot = getLowestRoot(a, b, c, t);
  55061. if (lowestRoot.found) {
  55062. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55063. if (f >= 0.0 && f <= 1.0) {
  55064. t = lowestRoot.root;
  55065. found = true;
  55066. this._edge.scaleInPlace(f);
  55067. p2.addToRef(this._edge, this._collisionPoint);
  55068. }
  55069. }
  55070. p1.subtractToRef(p3, this._edge);
  55071. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55072. edgeSquaredLength = this._edge.lengthSquared();
  55073. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55074. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55075. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55076. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55077. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55078. lowestRoot = getLowestRoot(a, b, c, t);
  55079. if (lowestRoot.found) {
  55080. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55081. if (f >= 0.0 && f <= 1.0) {
  55082. t = lowestRoot.root;
  55083. found = true;
  55084. this._edge.scaleInPlace(f);
  55085. p3.addToRef(this._edge, this._collisionPoint);
  55086. }
  55087. }
  55088. }
  55089. if (found) {
  55090. var distToCollision = t * this._velocity.length();
  55091. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55092. if (!this.intersectionPoint) {
  55093. this.intersectionPoint = this._collisionPoint.clone();
  55094. }
  55095. else {
  55096. this.intersectionPoint.copyFrom(this._collisionPoint);
  55097. }
  55098. this._nearestDistance = distToCollision;
  55099. this.collisionFound = true;
  55100. }
  55101. }
  55102. };
  55103. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55104. for (var i = indexStart; i < indexEnd; i += 3) {
  55105. var p1 = pts[indices[i] - decal];
  55106. var p2 = pts[indices[i + 1] - decal];
  55107. var p3 = pts[indices[i + 2] - decal];
  55108. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55109. }
  55110. };
  55111. Collider.prototype._getResponse = function (pos, vel) {
  55112. pos.addToRef(vel, this._destinationPoint);
  55113. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55114. this._basePoint.addToRef(vel, pos);
  55115. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55116. this._slidePlaneNormal.normalize();
  55117. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55118. pos.addInPlace(this._displacementVector);
  55119. this.intersectionPoint.addInPlace(this._displacementVector);
  55120. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55121. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55122. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55123. };
  55124. return Collider;
  55125. }());
  55126. BABYLON.Collider = Collider;
  55127. })(BABYLON || (BABYLON = {}));
  55128. //# sourceMappingURL=babylon.collider.js.map
  55129. var BABYLON;
  55130. (function (BABYLON) {
  55131. //WebWorker code will be inserted to this variable.
  55132. BABYLON.CollisionWorker = "";
  55133. /** Defines supported task for worker process */
  55134. var WorkerTaskType;
  55135. (function (WorkerTaskType) {
  55136. /** Initialization */
  55137. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55138. /** Update of geometry */
  55139. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55140. /** Evaluate collision */
  55141. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55142. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55143. /** Defines kind of replies returned by worker */
  55144. var WorkerReplyType;
  55145. (function (WorkerReplyType) {
  55146. /** Success */
  55147. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55148. /** Unkown error */
  55149. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55150. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55151. var CollisionCoordinatorWorker = /** @class */ (function () {
  55152. function CollisionCoordinatorWorker() {
  55153. var _this = this;
  55154. this._scaledPosition = BABYLON.Vector3.Zero();
  55155. this._scaledVelocity = BABYLON.Vector3.Zero();
  55156. this.onMeshUpdated = function (transformNode) {
  55157. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55158. };
  55159. this.onGeometryUpdated = function (geometry) {
  55160. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55161. };
  55162. this._afterRender = function () {
  55163. if (!_this._init)
  55164. return;
  55165. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55166. return;
  55167. }
  55168. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55169. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55170. if (_this._runningUpdated > 4) {
  55171. return;
  55172. }
  55173. ++_this._runningUpdated;
  55174. var payload = {
  55175. updatedMeshes: _this._addUpdateMeshesList,
  55176. updatedGeometries: _this._addUpdateGeometriesList,
  55177. removedGeometries: _this._toRemoveGeometryArray,
  55178. removedMeshes: _this._toRemoveMeshesArray
  55179. };
  55180. var message = {
  55181. payload: payload,
  55182. taskType: WorkerTaskType.UPDATE
  55183. };
  55184. var serializable = [];
  55185. for (var id in payload.updatedGeometries) {
  55186. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55187. //prepare transferables
  55188. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55189. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55190. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55191. }
  55192. }
  55193. _this._worker.postMessage(message, serializable);
  55194. _this._addUpdateMeshesList = {};
  55195. _this._addUpdateGeometriesList = {};
  55196. _this._toRemoveGeometryArray = [];
  55197. _this._toRemoveMeshesArray = [];
  55198. };
  55199. this._onMessageFromWorker = function (e) {
  55200. var returnData = e.data;
  55201. if (returnData.error != WorkerReplyType.SUCCESS) {
  55202. //TODO what errors can be returned from the worker?
  55203. BABYLON.Tools.Warn("error returned from worker!");
  55204. return;
  55205. }
  55206. switch (returnData.taskType) {
  55207. case WorkerTaskType.INIT:
  55208. _this._init = true;
  55209. //Update the worked with ALL of the scene's current state
  55210. _this._scene.meshes.forEach(function (mesh) {
  55211. _this.onMeshAdded(mesh);
  55212. });
  55213. _this._scene.getGeometries().forEach(function (geometry) {
  55214. _this.onGeometryAdded(geometry);
  55215. });
  55216. break;
  55217. case WorkerTaskType.UPDATE:
  55218. _this._runningUpdated--;
  55219. break;
  55220. case WorkerTaskType.COLLIDE:
  55221. var returnPayload = returnData.payload;
  55222. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55223. return;
  55224. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55225. if (callback) {
  55226. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55227. if (mesh) {
  55228. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55229. }
  55230. }
  55231. //cleanup
  55232. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55233. break;
  55234. }
  55235. };
  55236. this._collisionsCallbackArray = [];
  55237. this._init = false;
  55238. this._runningUpdated = 0;
  55239. this._addUpdateMeshesList = {};
  55240. this._addUpdateGeometriesList = {};
  55241. this._toRemoveGeometryArray = [];
  55242. this._toRemoveMeshesArray = [];
  55243. }
  55244. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55245. if (!this._init)
  55246. return;
  55247. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55248. return;
  55249. position.divideToRef(collider._radius, this._scaledPosition);
  55250. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55251. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55252. var payload = {
  55253. collider: {
  55254. position: this._scaledPosition.asArray(),
  55255. velocity: this._scaledVelocity.asArray(),
  55256. radius: collider._radius.asArray()
  55257. },
  55258. collisionId: collisionIndex,
  55259. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55260. maximumRetry: maximumRetry
  55261. };
  55262. var message = {
  55263. payload: payload,
  55264. taskType: WorkerTaskType.COLLIDE
  55265. };
  55266. this._worker.postMessage(message);
  55267. };
  55268. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55269. this._scene = scene;
  55270. this._scene.registerAfterRender(this._afterRender);
  55271. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55272. this._worker = new Worker(workerUrl);
  55273. this._worker.onmessage = this._onMessageFromWorker;
  55274. var message = {
  55275. payload: {},
  55276. taskType: WorkerTaskType.INIT
  55277. };
  55278. this._worker.postMessage(message);
  55279. };
  55280. CollisionCoordinatorWorker.prototype.destroy = function () {
  55281. this._scene.unregisterAfterRender(this._afterRender);
  55282. this._worker.terminate();
  55283. };
  55284. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55285. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55286. this.onMeshUpdated(mesh);
  55287. };
  55288. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55289. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55290. };
  55291. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55292. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55293. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55294. this.onGeometryUpdated(geometry);
  55295. };
  55296. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55297. this._toRemoveGeometryArray.push(geometry.id);
  55298. };
  55299. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55300. var submeshes = [];
  55301. if (mesh.subMeshes) {
  55302. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55303. var boundingInfo = sm.getBoundingInfo();
  55304. return {
  55305. position: idx,
  55306. verticesStart: sm.verticesStart,
  55307. verticesCount: sm.verticesCount,
  55308. indexStart: sm.indexStart,
  55309. indexCount: sm.indexCount,
  55310. hasMaterial: !!sm.getMaterial(),
  55311. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55312. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55313. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55314. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55315. };
  55316. });
  55317. }
  55318. var geometryId = null;
  55319. if (mesh instanceof BABYLON.Mesh) {
  55320. var geometry = mesh.geometry;
  55321. geometryId = geometry ? geometry.id : null;
  55322. }
  55323. else if (mesh instanceof BABYLON.InstancedMesh) {
  55324. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55325. geometryId = geometry ? geometry.id : null;
  55326. }
  55327. var boundingInfo = mesh.getBoundingInfo();
  55328. return {
  55329. uniqueId: mesh.uniqueId,
  55330. id: mesh.id,
  55331. name: mesh.name,
  55332. geometryId: geometryId,
  55333. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55334. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55335. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55336. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55337. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55338. subMeshes: submeshes,
  55339. checkCollisions: mesh.checkCollisions
  55340. };
  55341. };
  55342. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55343. return {
  55344. id: geometry.id,
  55345. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55346. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55347. indices: new Uint32Array(geometry.getIndices() || []),
  55348. };
  55349. };
  55350. return CollisionCoordinatorWorker;
  55351. }());
  55352. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55353. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55354. function CollisionCoordinatorLegacy() {
  55355. this._scaledPosition = BABYLON.Vector3.Zero();
  55356. this._scaledVelocity = BABYLON.Vector3.Zero();
  55357. this._finalPosition = BABYLON.Vector3.Zero();
  55358. }
  55359. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55360. position.divideToRef(collider._radius, this._scaledPosition);
  55361. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55362. collider.collidedMesh = null;
  55363. collider._retry = 0;
  55364. collider._initialVelocity = this._scaledVelocity;
  55365. collider._initialPosition = this._scaledPosition;
  55366. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55367. this._finalPosition.multiplyInPlace(collider._radius);
  55368. //run the callback
  55369. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55370. };
  55371. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55372. this._scene = scene;
  55373. };
  55374. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55375. //Legacy need no destruction method.
  55376. };
  55377. //No update in legacy mode
  55378. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55379. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55380. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55381. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55382. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55383. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55384. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55385. if (excludedMesh === void 0) { excludedMesh = null; }
  55386. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55387. if (collider._retry >= maximumRetry) {
  55388. finalPosition.copyFrom(position);
  55389. return;
  55390. }
  55391. // Check if this is a mesh else camera or -1
  55392. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55393. collider._initialize(position, velocity, closeDistance);
  55394. // Check all meshes
  55395. for (var index = 0; index < this._scene.meshes.length; index++) {
  55396. var mesh = this._scene.meshes[index];
  55397. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55398. mesh._checkCollision(collider);
  55399. }
  55400. }
  55401. if (!collider.collisionFound) {
  55402. position.addToRef(velocity, finalPosition);
  55403. return;
  55404. }
  55405. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55406. collider._getResponse(position, velocity);
  55407. }
  55408. if (velocity.length() <= closeDistance) {
  55409. finalPosition.copyFrom(position);
  55410. return;
  55411. }
  55412. collider._retry++;
  55413. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55414. };
  55415. return CollisionCoordinatorLegacy;
  55416. }());
  55417. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55418. })(BABYLON || (BABYLON = {}));
  55419. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55420. var BABYLON;
  55421. (function (BABYLON) {
  55422. /**
  55423. * A particle represents one of the element emitted by a particle system.
  55424. * This is mainly define by its coordinates, direction, velocity and age.
  55425. */
  55426. var Particle = /** @class */ (function () {
  55427. /**
  55428. * Creates a new instance Particle
  55429. * @param particleSystem the particle system the particle belongs to
  55430. */
  55431. function Particle(
  55432. /**
  55433. * particleSystem the particle system the particle belongs to.
  55434. */
  55435. particleSystem) {
  55436. this.particleSystem = particleSystem;
  55437. /**
  55438. * The world position of the particle in the scene.
  55439. */
  55440. this.position = BABYLON.Vector3.Zero();
  55441. /**
  55442. * The world direction of the particle in the scene.
  55443. */
  55444. this.direction = BABYLON.Vector3.Zero();
  55445. /**
  55446. * The color of the particle.
  55447. */
  55448. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55449. /**
  55450. * The color change of the particle per step.
  55451. */
  55452. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55453. /**
  55454. * Defines how long will the life of the particle be.
  55455. */
  55456. this.lifeTime = 1.0;
  55457. /**
  55458. * The current age of the particle.
  55459. */
  55460. this.age = 0;
  55461. /**
  55462. * The current size of the particle.
  55463. */
  55464. this.size = 0;
  55465. /**
  55466. * The current angle of the particle.
  55467. */
  55468. this.angle = 0;
  55469. /**
  55470. * Defines how fast is the angle changing.
  55471. */
  55472. this.angularSpeed = 0;
  55473. /**
  55474. * Defines the cell index used by the particle to be rendered from a sprite.
  55475. */
  55476. this.cellIndex = 0;
  55477. this._currentFrameCounter = 0;
  55478. if (!this.particleSystem.isAnimationSheetEnabled) {
  55479. return;
  55480. }
  55481. this.updateCellInfoFromSystem();
  55482. }
  55483. Particle.prototype.updateCellInfoFromSystem = function () {
  55484. this.cellIndex = this.particleSystem.startSpriteCellID;
  55485. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55486. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55487. }
  55488. else {
  55489. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55490. }
  55491. };
  55492. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55493. // (ageOffset / scaledUpdateSpeed) / available cells
  55494. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55495. this._currentFrameCounter += scaledUpdateSpeed;
  55496. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55497. this._currentFrameCounter = 0;
  55498. this.cellIndex++;
  55499. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55500. this.cellIndex = this.particleSystem.endSpriteCellID;
  55501. }
  55502. }
  55503. };
  55504. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55505. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55506. this.cellIndex++;
  55507. this._currentFrameCounter = 0;
  55508. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55509. if (this.particleSystem.spriteCellLoop) {
  55510. this.cellIndex = this.particleSystem.startSpriteCellID;
  55511. }
  55512. else {
  55513. this.cellIndex = this.particleSystem.endSpriteCellID;
  55514. }
  55515. }
  55516. }
  55517. else {
  55518. this._currentFrameCounter++;
  55519. }
  55520. };
  55521. /**
  55522. * Copy the properties of particle to another one.
  55523. * @param other the particle to copy the information to.
  55524. */
  55525. Particle.prototype.copyTo = function (other) {
  55526. other.position.copyFrom(this.position);
  55527. other.direction.copyFrom(this.direction);
  55528. other.color.copyFrom(this.color);
  55529. other.colorStep.copyFrom(this.colorStep);
  55530. other.lifeTime = this.lifeTime;
  55531. other.age = this.age;
  55532. other.size = this.size;
  55533. other.angle = this.angle;
  55534. other.angularSpeed = this.angularSpeed;
  55535. other.particleSystem = this.particleSystem;
  55536. other.cellIndex = this.cellIndex;
  55537. };
  55538. return Particle;
  55539. }());
  55540. BABYLON.Particle = Particle;
  55541. })(BABYLON || (BABYLON = {}));
  55542. //# sourceMappingURL=babylon.particle.js.map
  55543. var BABYLON;
  55544. (function (BABYLON) {
  55545. /**
  55546. * This represents a particle system in Babylon.
  55547. * 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.
  55548. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55549. * @example https://doc.babylonjs.com/babylon101/particles
  55550. */
  55551. var ParticleSystem = /** @class */ (function () {
  55552. /**
  55553. * Instantiates a particle system.
  55554. * 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.
  55555. * @param name The name of the particle system
  55556. * @param capacity The max number of particles alive at the same time
  55557. * @param scene The scene the particle system belongs to
  55558. * @param customEffect a custom effect used to change the way particles are rendered by default
  55559. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55560. * @param epsilon Offset used to render the particles
  55561. */
  55562. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55563. if (customEffect === void 0) { customEffect = null; }
  55564. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55565. if (epsilon === void 0) { epsilon = 0.01; }
  55566. var _this = this;
  55567. /**
  55568. * List of animations used by the particle system.
  55569. */
  55570. this.animations = [];
  55571. /**
  55572. * The rendering group used by the Particle system to chose when to render.
  55573. */
  55574. this.renderingGroupId = 0;
  55575. /**
  55576. * The emitter represents the Mesh or position we are attaching the particle system to.
  55577. */
  55578. this.emitter = null;
  55579. /**
  55580. * The maximum number of particles to emit per frame
  55581. */
  55582. this.emitRate = 10;
  55583. /**
  55584. * If you want to launch only a few particles at once, that can be done, as well.
  55585. */
  55586. this.manualEmitCount = -1;
  55587. /**
  55588. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55589. */
  55590. this.updateSpeed = 0.01;
  55591. /**
  55592. * The amount of time the particle system is running (depends of the overall update speed).
  55593. */
  55594. this.targetStopDuration = 0;
  55595. /**
  55596. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55597. */
  55598. this.disposeOnStop = false;
  55599. /**
  55600. * Minimum power of emitting particles.
  55601. */
  55602. this.minEmitPower = 1;
  55603. /**
  55604. * Maximum power of emitting particles.
  55605. */
  55606. this.maxEmitPower = 1;
  55607. /**
  55608. * Minimum life time of emitting particles.
  55609. */
  55610. this.minLifeTime = 1;
  55611. /**
  55612. * Maximum life time of emitting particles.
  55613. */
  55614. this.maxLifeTime = 1;
  55615. /**
  55616. * Minimum Size of emitting particles.
  55617. */
  55618. this.minSize = 1;
  55619. /**
  55620. * Maximum Size of emitting particles.
  55621. */
  55622. this.maxSize = 1;
  55623. /**
  55624. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55625. */
  55626. this.minAngularSpeed = 0;
  55627. /**
  55628. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55629. */
  55630. this.maxAngularSpeed = 0;
  55631. /**
  55632. * The layer mask we are rendering the particles through.
  55633. */
  55634. this.layerMask = 0x0FFFFFFF;
  55635. /**
  55636. * This can help using your own shader to render the particle system.
  55637. * The according effect will be created
  55638. */
  55639. this.customShader = null;
  55640. /**
  55641. * By default particle system starts as soon as they are created. This prevents the
  55642. * automatic start to happen and let you decide when to start emitting particles.
  55643. */
  55644. this.preventAutoStart = false;
  55645. /**
  55646. * Callback triggered when the particle animation is ending.
  55647. */
  55648. this.onAnimationEnd = null;
  55649. /**
  55650. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55651. */
  55652. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55653. /**
  55654. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55655. * to override the particles.
  55656. */
  55657. this.forceDepthWrite = false;
  55658. /**
  55659. * You can use gravity if you want to give an orientation to your particles.
  55660. */
  55661. this.gravity = BABYLON.Vector3.Zero();
  55662. /**
  55663. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55664. */
  55665. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55666. /**
  55667. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55668. */
  55669. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55670. /**
  55671. * Color the particle will have at the end of its lifetime.
  55672. */
  55673. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55674. /**
  55675. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55676. */
  55677. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55678. /**
  55679. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55680. */
  55681. this.spriteCellLoop = true;
  55682. /**
  55683. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55684. */
  55685. this.spriteCellChangeSpeed = 0;
  55686. /**
  55687. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55688. */
  55689. this.startSpriteCellID = 0;
  55690. /**
  55691. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55692. */
  55693. this.endSpriteCellID = 0;
  55694. /**
  55695. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55696. */
  55697. this.spriteCellWidth = 0;
  55698. /**
  55699. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55700. */
  55701. this.spriteCellHeight = 0;
  55702. /**
  55703. * An event triggered when the system is disposed.
  55704. */
  55705. this.onDisposeObservable = new BABYLON.Observable();
  55706. this._particles = new Array();
  55707. this._stockParticles = new Array();
  55708. this._newPartsExcess = 0;
  55709. this._vertexBuffers = {};
  55710. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55711. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55712. this._scaledDirection = BABYLON.Vector3.Zero();
  55713. this._scaledGravity = BABYLON.Vector3.Zero();
  55714. this._currentRenderId = -1;
  55715. this._started = false;
  55716. this._stopped = false;
  55717. this._actualFrame = 0;
  55718. this._vertexBufferSize = 11;
  55719. // start of sub system methods
  55720. /**
  55721. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55722. * Its lifetime will start back at 0.
  55723. */
  55724. this.recycleParticle = function (particle) {
  55725. var lastParticle = _this._particles.pop();
  55726. if (lastParticle !== particle) {
  55727. lastParticle.copyTo(particle);
  55728. }
  55729. _this._stockParticles.push(lastParticle);
  55730. };
  55731. this._createParticle = function () {
  55732. var particle;
  55733. if (_this._stockParticles.length !== 0) {
  55734. particle = _this._stockParticles.pop();
  55735. particle.age = 0;
  55736. particle.cellIndex = _this.startSpriteCellID;
  55737. }
  55738. else {
  55739. particle = new BABYLON.Particle(_this);
  55740. }
  55741. return particle;
  55742. };
  55743. this._emitFromParticle = function (particle) {
  55744. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55745. return;
  55746. }
  55747. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55748. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55749. subSystem._rootParticleSystem = _this;
  55750. _this.activeSubSystems.push(subSystem);
  55751. subSystem.start();
  55752. };
  55753. this._appendParticleVertexes = null;
  55754. this.id = name;
  55755. this.name = name;
  55756. this._capacity = capacity;
  55757. this._epsilon = epsilon;
  55758. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55759. if (isAnimationSheetEnabled) {
  55760. this._vertexBufferSize = 12;
  55761. }
  55762. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55763. this._customEffect = customEffect;
  55764. scene.particleSystems.push(this);
  55765. this._createIndexBuffer();
  55766. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55767. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55768. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55769. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55770. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55771. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55772. if (this._isAnimationSheetEnabled) {
  55773. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55774. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55775. }
  55776. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55777. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55778. this._vertexBuffers["options"] = options;
  55779. // Default emitter type
  55780. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55781. this.updateFunction = function (particles) {
  55782. for (var index = 0; index < particles.length; index++) {
  55783. var particle = particles[index];
  55784. particle.age += _this._scaledUpdateSpeed;
  55785. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55786. _this._emitFromParticle(particle);
  55787. _this.recycleParticle(particle);
  55788. index--;
  55789. continue;
  55790. }
  55791. else {
  55792. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55793. particle.color.addInPlace(_this._scaledColorStep);
  55794. if (particle.color.a < 0)
  55795. particle.color.a = 0;
  55796. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55797. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55798. particle.position.addInPlace(_this._scaledDirection);
  55799. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55800. particle.direction.addInPlace(_this._scaledGravity);
  55801. if (_this._isAnimationSheetEnabled) {
  55802. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55803. }
  55804. }
  55805. }
  55806. };
  55807. }
  55808. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55809. /**
  55810. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55811. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55812. */
  55813. get: function () {
  55814. if (this.particleEmitterType.direction1) {
  55815. return this.particleEmitterType.direction1;
  55816. }
  55817. return BABYLON.Vector3.Zero();
  55818. },
  55819. set: function (value) {
  55820. if (this.particleEmitterType.direction1) {
  55821. this.particleEmitterType.direction1 = value;
  55822. }
  55823. },
  55824. enumerable: true,
  55825. configurable: true
  55826. });
  55827. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55828. /**
  55829. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55830. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55831. */
  55832. get: function () {
  55833. if (this.particleEmitterType.direction2) {
  55834. return this.particleEmitterType.direction2;
  55835. }
  55836. return BABYLON.Vector3.Zero();
  55837. },
  55838. set: function (value) {
  55839. if (this.particleEmitterType.direction2) {
  55840. this.particleEmitterType.direction2 = value;
  55841. }
  55842. },
  55843. enumerable: true,
  55844. configurable: true
  55845. });
  55846. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55847. /**
  55848. * 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.
  55849. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55850. */
  55851. get: function () {
  55852. if (this.particleEmitterType.minEmitBox) {
  55853. return this.particleEmitterType.minEmitBox;
  55854. }
  55855. return BABYLON.Vector3.Zero();
  55856. },
  55857. set: function (value) {
  55858. if (this.particleEmitterType.minEmitBox) {
  55859. this.particleEmitterType.minEmitBox = value;
  55860. }
  55861. },
  55862. enumerable: true,
  55863. configurable: true
  55864. });
  55865. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55866. /**
  55867. * 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.
  55868. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55869. */
  55870. get: function () {
  55871. if (this.particleEmitterType.maxEmitBox) {
  55872. return this.particleEmitterType.maxEmitBox;
  55873. }
  55874. return BABYLON.Vector3.Zero();
  55875. },
  55876. set: function (value) {
  55877. if (this.particleEmitterType.maxEmitBox) {
  55878. this.particleEmitterType.maxEmitBox = value;
  55879. }
  55880. },
  55881. enumerable: true,
  55882. configurable: true
  55883. });
  55884. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55885. /**
  55886. * Sets a callback that will be triggered when the system is disposed.
  55887. */
  55888. set: function (callback) {
  55889. if (this._onDisposeObserver) {
  55890. this.onDisposeObservable.remove(this._onDisposeObserver);
  55891. }
  55892. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55893. },
  55894. enumerable: true,
  55895. configurable: true
  55896. });
  55897. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55898. /**
  55899. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55900. */
  55901. get: function () {
  55902. return this._isAnimationSheetEnabled;
  55903. },
  55904. enumerable: true,
  55905. configurable: true
  55906. });
  55907. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55908. //end of Sub-emitter
  55909. /**
  55910. * Gets the current list of active particles
  55911. */
  55912. get: function () {
  55913. return this._particles;
  55914. },
  55915. enumerable: true,
  55916. configurable: true
  55917. });
  55918. /**
  55919. * Returns the string "ParticleSystem"
  55920. * @returns a string containing the class name
  55921. */
  55922. ParticleSystem.prototype.getClassName = function () {
  55923. return "ParticleSystem";
  55924. };
  55925. ParticleSystem.prototype._createIndexBuffer = function () {
  55926. var indices = [];
  55927. var index = 0;
  55928. for (var count = 0; count < this._capacity; count++) {
  55929. indices.push(index);
  55930. indices.push(index + 1);
  55931. indices.push(index + 2);
  55932. indices.push(index);
  55933. indices.push(index + 2);
  55934. indices.push(index + 3);
  55935. index += 4;
  55936. }
  55937. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55938. };
  55939. /**
  55940. * Gets the maximum number of particles active at the same time.
  55941. * @returns The max number of active particles.
  55942. */
  55943. ParticleSystem.prototype.getCapacity = function () {
  55944. return this._capacity;
  55945. };
  55946. /**
  55947. * Gets Wether there are still active particles in the system.
  55948. * @returns True if it is alive, otherwise false.
  55949. */
  55950. ParticleSystem.prototype.isAlive = function () {
  55951. return this._alive;
  55952. };
  55953. /**
  55954. * Gets Wether the system has been started.
  55955. * @returns True if it has been started, otherwise false.
  55956. */
  55957. ParticleSystem.prototype.isStarted = function () {
  55958. return this._started;
  55959. };
  55960. /**
  55961. * Starts the particle system and begins to emit.
  55962. */
  55963. ParticleSystem.prototype.start = function () {
  55964. this._started = true;
  55965. this._stopped = false;
  55966. this._actualFrame = 0;
  55967. if (this.subEmitters && this.subEmitters.length != 0) {
  55968. this.activeSubSystems = new Array();
  55969. }
  55970. };
  55971. /**
  55972. * Stops the particle system.
  55973. * @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.
  55974. */
  55975. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55976. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55977. this._stopped = true;
  55978. if (stopSubEmitters) {
  55979. this._stopSubEmitters();
  55980. }
  55981. };
  55982. // animation sheet
  55983. /**
  55984. * Remove all active particles
  55985. */
  55986. ParticleSystem.prototype.reset = function () {
  55987. this._stockParticles = [];
  55988. this._particles = [];
  55989. };
  55990. /**
  55991. * @hidden (for internal use only)
  55992. */
  55993. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55994. var offset = index * this._vertexBufferSize;
  55995. this._vertexData[offset] = particle.position.x;
  55996. this._vertexData[offset + 1] = particle.position.y;
  55997. this._vertexData[offset + 2] = particle.position.z;
  55998. this._vertexData[offset + 3] = particle.color.r;
  55999. this._vertexData[offset + 4] = particle.color.g;
  56000. this._vertexData[offset + 5] = particle.color.b;
  56001. this._vertexData[offset + 6] = particle.color.a;
  56002. this._vertexData[offset + 7] = particle.angle;
  56003. this._vertexData[offset + 8] = particle.size;
  56004. this._vertexData[offset + 9] = offsetX;
  56005. this._vertexData[offset + 10] = offsetY;
  56006. };
  56007. /**
  56008. * @hidden (for internal use only)
  56009. */
  56010. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56011. if (offsetX === 0)
  56012. offsetX = this._epsilon;
  56013. else if (offsetX === 1)
  56014. offsetX = 1 - this._epsilon;
  56015. if (offsetY === 0)
  56016. offsetY = this._epsilon;
  56017. else if (offsetY === 1)
  56018. offsetY = 1 - this._epsilon;
  56019. var offset = index * this._vertexBufferSize;
  56020. this._vertexData[offset] = particle.position.x;
  56021. this._vertexData[offset + 1] = particle.position.y;
  56022. this._vertexData[offset + 2] = particle.position.z;
  56023. this._vertexData[offset + 3] = particle.color.r;
  56024. this._vertexData[offset + 4] = particle.color.g;
  56025. this._vertexData[offset + 5] = particle.color.b;
  56026. this._vertexData[offset + 6] = particle.color.a;
  56027. this._vertexData[offset + 7] = particle.angle;
  56028. this._vertexData[offset + 8] = particle.size;
  56029. this._vertexData[offset + 9] = offsetX;
  56030. this._vertexData[offset + 10] = offsetY;
  56031. this._vertexData[offset + 11] = particle.cellIndex;
  56032. };
  56033. ParticleSystem.prototype._stopSubEmitters = function () {
  56034. if (!this.activeSubSystems) {
  56035. return;
  56036. }
  56037. this.activeSubSystems.forEach(function (subSystem) {
  56038. subSystem.stop(true);
  56039. });
  56040. this.activeSubSystems = new Array();
  56041. };
  56042. ParticleSystem.prototype._removeFromRoot = function () {
  56043. if (!this._rootParticleSystem) {
  56044. return;
  56045. }
  56046. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56047. if (index !== -1) {
  56048. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56049. }
  56050. };
  56051. // end of sub system methods
  56052. ParticleSystem.prototype._update = function (newParticles) {
  56053. // Update current
  56054. this._alive = this._particles.length > 0;
  56055. this.updateFunction(this._particles);
  56056. // Add new ones
  56057. var worldMatrix;
  56058. if (this.emitter.position) {
  56059. var emitterMesh = this.emitter;
  56060. worldMatrix = emitterMesh.getWorldMatrix();
  56061. }
  56062. else {
  56063. var emitterPosition = this.emitter;
  56064. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56065. }
  56066. var particle;
  56067. for (var index = 0; index < newParticles; index++) {
  56068. if (this._particles.length === this._capacity) {
  56069. break;
  56070. }
  56071. particle = this._createParticle();
  56072. this._particles.push(particle);
  56073. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56074. if (this.startPositionFunction) {
  56075. this.startPositionFunction(worldMatrix, particle.position, particle);
  56076. }
  56077. else {
  56078. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56079. }
  56080. if (this.startDirectionFunction) {
  56081. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56082. }
  56083. else {
  56084. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56085. }
  56086. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56087. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56088. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56089. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56090. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56091. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56092. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56093. }
  56094. };
  56095. ParticleSystem.prototype._getEffect = function () {
  56096. if (this._customEffect) {
  56097. return this._customEffect;
  56098. }
  56099. ;
  56100. var defines = [];
  56101. if (this._scene.clipPlane) {
  56102. defines.push("#define CLIPPLANE");
  56103. }
  56104. if (this._isAnimationSheetEnabled) {
  56105. defines.push("#define ANIMATESHEET");
  56106. }
  56107. // Effect
  56108. var join = defines.join("\n");
  56109. if (this._cachedDefines !== join) {
  56110. this._cachedDefines = join;
  56111. var attributesNamesOrOptions;
  56112. var effectCreationOption;
  56113. if (this._isAnimationSheetEnabled) {
  56114. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56115. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56116. }
  56117. else {
  56118. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56119. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56120. }
  56121. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56122. }
  56123. return this._effect;
  56124. };
  56125. /**
  56126. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56127. */
  56128. ParticleSystem.prototype.animate = function () {
  56129. if (!this._started)
  56130. return;
  56131. var effect = this._getEffect();
  56132. // Check
  56133. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56134. return;
  56135. if (this._currentRenderId === this._scene.getRenderId()) {
  56136. return;
  56137. }
  56138. this._currentRenderId = this._scene.getRenderId();
  56139. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56140. // determine the number of particles we need to create
  56141. var newParticles;
  56142. if (this.manualEmitCount > -1) {
  56143. newParticles = this.manualEmitCount;
  56144. this._newPartsExcess = 0;
  56145. this.manualEmitCount = 0;
  56146. }
  56147. else {
  56148. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56149. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56150. }
  56151. if (this._newPartsExcess > 1.0) {
  56152. newParticles += this._newPartsExcess >> 0;
  56153. this._newPartsExcess -= this._newPartsExcess >> 0;
  56154. }
  56155. this._alive = false;
  56156. if (!this._stopped) {
  56157. this._actualFrame += this._scaledUpdateSpeed;
  56158. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56159. this.stop();
  56160. }
  56161. else {
  56162. newParticles = 0;
  56163. }
  56164. this._update(newParticles);
  56165. // Stopped?
  56166. if (this._stopped) {
  56167. if (!this._alive) {
  56168. this._started = false;
  56169. if (this.onAnimationEnd) {
  56170. this.onAnimationEnd();
  56171. }
  56172. if (this.disposeOnStop) {
  56173. this._scene._toBeDisposed.push(this);
  56174. }
  56175. }
  56176. }
  56177. // Animation sheet
  56178. if (this._isAnimationSheetEnabled) {
  56179. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56180. }
  56181. else {
  56182. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56183. }
  56184. // Update VBO
  56185. var offset = 0;
  56186. for (var index = 0; index < this._particles.length; index++) {
  56187. var particle = this._particles[index];
  56188. this._appendParticleVertexes(offset, particle);
  56189. offset += 4;
  56190. }
  56191. if (this._vertexBuffer) {
  56192. this._vertexBuffer.update(this._vertexData);
  56193. }
  56194. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56195. this.stop();
  56196. }
  56197. };
  56198. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56199. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56200. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56201. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56202. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56203. };
  56204. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56205. this._appendParticleVertex(offset++, particle, 0, 0);
  56206. this._appendParticleVertex(offset++, particle, 1, 0);
  56207. this._appendParticleVertex(offset++, particle, 1, 1);
  56208. this._appendParticleVertex(offset++, particle, 0, 1);
  56209. };
  56210. /**
  56211. * Rebuilds the particle system.
  56212. */
  56213. ParticleSystem.prototype.rebuild = function () {
  56214. this._createIndexBuffer();
  56215. if (this._vertexBuffer) {
  56216. this._vertexBuffer._rebuild();
  56217. }
  56218. };
  56219. /**
  56220. * Is this system ready to be used/rendered
  56221. * @return true if the system is ready
  56222. */
  56223. ParticleSystem.prototype.isReady = function () {
  56224. var effect = this._getEffect();
  56225. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56226. return false;
  56227. }
  56228. return true;
  56229. };
  56230. /**
  56231. * Renders the particle system in its current state.
  56232. * @returns the current number of particles
  56233. */
  56234. ParticleSystem.prototype.render = function () {
  56235. var effect = this._getEffect();
  56236. // Check
  56237. if (!this.isReady() || !this._particles.length) {
  56238. return 0;
  56239. }
  56240. var engine = this._scene.getEngine();
  56241. // Render
  56242. engine.enableEffect(effect);
  56243. engine.setState(false);
  56244. var viewMatrix = this._scene.getViewMatrix();
  56245. effect.setTexture("diffuseSampler", this.particleTexture);
  56246. effect.setMatrix("view", viewMatrix);
  56247. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56248. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56249. var baseSize = this.particleTexture.getBaseSize();
  56250. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56251. }
  56252. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56253. if (this._scene.clipPlane) {
  56254. var clipPlane = this._scene.clipPlane;
  56255. var invView = viewMatrix.clone();
  56256. invView.invert();
  56257. effect.setMatrix("invView", invView);
  56258. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56259. }
  56260. // VBOs
  56261. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56262. // Draw order
  56263. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56264. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56265. }
  56266. else {
  56267. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56268. }
  56269. if (this.forceDepthWrite) {
  56270. engine.setDepthWrite(true);
  56271. }
  56272. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56273. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56274. return this._particles.length;
  56275. };
  56276. /**
  56277. * Disposes the particle system and free the associated resources
  56278. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56279. */
  56280. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56281. if (disposeTexture === void 0) { disposeTexture = true; }
  56282. if (this._vertexBuffer) {
  56283. this._vertexBuffer.dispose();
  56284. this._vertexBuffer = null;
  56285. }
  56286. if (this._indexBuffer) {
  56287. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56288. this._indexBuffer = null;
  56289. }
  56290. if (disposeTexture && this.particleTexture) {
  56291. this.particleTexture.dispose();
  56292. this.particleTexture = null;
  56293. }
  56294. this._removeFromRoot();
  56295. // Remove from scene
  56296. var index = this._scene.particleSystems.indexOf(this);
  56297. if (index > -1) {
  56298. this._scene.particleSystems.splice(index, 1);
  56299. }
  56300. // Callback
  56301. this.onDisposeObservable.notifyObservers(this);
  56302. this.onDisposeObservable.clear();
  56303. };
  56304. /**
  56305. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56306. * @param radius The radius of the sphere to emit from
  56307. * @returns the emitter
  56308. */
  56309. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56310. if (radius === void 0) { radius = 1; }
  56311. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56312. this.particleEmitterType = particleEmitter;
  56313. return particleEmitter;
  56314. };
  56315. /**
  56316. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56317. * @param radius The radius of the sphere to emit from
  56318. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56319. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56320. * @returns the emitter
  56321. */
  56322. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56323. if (radius === void 0) { radius = 1; }
  56324. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56325. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56326. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56327. this.particleEmitterType = particleEmitter;
  56328. return particleEmitter;
  56329. };
  56330. /**
  56331. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56332. * @param radius The radius of the cone to emit from
  56333. * @param angle The base angle of the cone
  56334. * @returns the emitter
  56335. */
  56336. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56337. if (radius === void 0) { radius = 1; }
  56338. if (angle === void 0) { angle = Math.PI / 4; }
  56339. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56340. this.particleEmitterType = particleEmitter;
  56341. return particleEmitter;
  56342. };
  56343. // 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.
  56344. /**
  56345. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56346. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56347. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56348. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56349. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56350. * @returns the emitter
  56351. */
  56352. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56353. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56354. this.particleEmitterType = particleEmitter;
  56355. this.direction1 = direction1;
  56356. this.direction2 = direction2;
  56357. this.minEmitBox = minEmitBox;
  56358. this.maxEmitBox = maxEmitBox;
  56359. return particleEmitter;
  56360. };
  56361. // Clone
  56362. /**
  56363. * Clones the particle system.
  56364. * @param name The name of the cloned object
  56365. * @param newEmitter The new emitter to use
  56366. * @returns the cloned particle system
  56367. */
  56368. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56369. var custom = null;
  56370. var program = null;
  56371. if (this.customShader != null) {
  56372. program = this.customShader;
  56373. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56374. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56375. }
  56376. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56377. result.customShader = program;
  56378. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56379. if (newEmitter === undefined) {
  56380. newEmitter = this.emitter;
  56381. }
  56382. result.emitter = newEmitter;
  56383. if (this.particleTexture) {
  56384. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56385. }
  56386. if (!this.preventAutoStart) {
  56387. result.start();
  56388. }
  56389. return result;
  56390. };
  56391. /**
  56392. * Serializes the particle system to a JSON object.
  56393. * @returns the JSON object
  56394. */
  56395. ParticleSystem.prototype.serialize = function () {
  56396. var serializationObject = {};
  56397. serializationObject.name = this.name;
  56398. serializationObject.id = this.id;
  56399. // Emitter
  56400. if (this.emitter.position) {
  56401. var emitterMesh = this.emitter;
  56402. serializationObject.emitterId = emitterMesh.id;
  56403. }
  56404. else {
  56405. var emitterPosition = this.emitter;
  56406. serializationObject.emitter = emitterPosition.asArray();
  56407. }
  56408. serializationObject.capacity = this.getCapacity();
  56409. if (this.particleTexture) {
  56410. serializationObject.textureName = this.particleTexture.name;
  56411. }
  56412. // Animations
  56413. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56414. // Particle system
  56415. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56416. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56417. serializationObject.minSize = this.minSize;
  56418. serializationObject.maxSize = this.maxSize;
  56419. serializationObject.minEmitPower = this.minEmitPower;
  56420. serializationObject.maxEmitPower = this.maxEmitPower;
  56421. serializationObject.minLifeTime = this.minLifeTime;
  56422. serializationObject.maxLifeTime = this.maxLifeTime;
  56423. serializationObject.emitRate = this.emitRate;
  56424. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56425. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56426. serializationObject.gravity = this.gravity.asArray();
  56427. serializationObject.direction1 = this.direction1.asArray();
  56428. serializationObject.direction2 = this.direction2.asArray();
  56429. serializationObject.color1 = this.color1.asArray();
  56430. serializationObject.color2 = this.color2.asArray();
  56431. serializationObject.colorDead = this.colorDead.asArray();
  56432. serializationObject.updateSpeed = this.updateSpeed;
  56433. serializationObject.targetStopDuration = this.targetStopDuration;
  56434. serializationObject.textureMask = this.textureMask.asArray();
  56435. serializationObject.blendMode = this.blendMode;
  56436. serializationObject.customShader = this.customShader;
  56437. serializationObject.preventAutoStart = this.preventAutoStart;
  56438. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56439. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56440. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56441. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56442. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56443. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56444. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56445. // Emitter
  56446. if (this.particleEmitterType) {
  56447. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56448. }
  56449. return serializationObject;
  56450. };
  56451. /**
  56452. * Parses a JSON object to create a particle system.
  56453. * @param parsedParticleSystem The JSON object to parse
  56454. * @param scene The scene to create the particle system in
  56455. * @param rootUrl The root url to use to load external dependencies like texture
  56456. * @returns the Parsed particle system
  56457. */
  56458. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56459. var name = parsedParticleSystem.name;
  56460. var custom = null;
  56461. var program = null;
  56462. if (parsedParticleSystem.customShader) {
  56463. program = parsedParticleSystem.customShader;
  56464. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56465. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56466. }
  56467. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56468. particleSystem.customShader = program;
  56469. if (parsedParticleSystem.id) {
  56470. particleSystem.id = parsedParticleSystem.id;
  56471. }
  56472. // Auto start
  56473. if (parsedParticleSystem.preventAutoStart) {
  56474. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56475. }
  56476. // Texture
  56477. if (parsedParticleSystem.textureName) {
  56478. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56479. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56480. }
  56481. // Emitter
  56482. if (parsedParticleSystem.emitterId) {
  56483. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56484. }
  56485. else {
  56486. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56487. }
  56488. // Animations
  56489. if (parsedParticleSystem.animations) {
  56490. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56491. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56492. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56493. }
  56494. }
  56495. if (parsedParticleSystem.autoAnimate) {
  56496. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56497. }
  56498. // Particle system
  56499. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56500. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56501. particleSystem.minSize = parsedParticleSystem.minSize;
  56502. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56503. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56504. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56505. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56506. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56507. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56508. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56509. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56510. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56511. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56512. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56513. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56514. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56515. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56516. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56517. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56518. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56519. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56520. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56521. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56522. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56523. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56524. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56525. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56526. if (!particleSystem.preventAutoStart) {
  56527. particleSystem.start();
  56528. }
  56529. return particleSystem;
  56530. };
  56531. /**
  56532. * Source color is added to the destination color without alpha affecting the result.
  56533. */
  56534. ParticleSystem.BLENDMODE_ONEONE = 0;
  56535. /**
  56536. * Blend current color and particle color using particle’s alpha.
  56537. */
  56538. ParticleSystem.BLENDMODE_STANDARD = 1;
  56539. return ParticleSystem;
  56540. }());
  56541. BABYLON.ParticleSystem = ParticleSystem;
  56542. })(BABYLON || (BABYLON = {}));
  56543. //# sourceMappingURL=babylon.particleSystem.js.map
  56544. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56545. var BABYLON;
  56546. (function (BABYLON) {
  56547. /**
  56548. * Particle emitter emitting particles from the inside of a box.
  56549. * It emits the particles randomly between 2 given directions.
  56550. */
  56551. var BoxParticleEmitter = /** @class */ (function () {
  56552. /**
  56553. * Creates a new instance BoxParticleEmitter
  56554. */
  56555. function BoxParticleEmitter() {
  56556. /**
  56557. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56558. */
  56559. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56560. /**
  56561. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56562. */
  56563. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56564. /**
  56565. * 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.
  56566. */
  56567. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56568. /**
  56569. * 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.
  56570. */
  56571. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56572. }
  56573. /**
  56574. * Called by the particle System when the direction is computed for the created particle.
  56575. * @param emitPower is the power of the particle (speed)
  56576. * @param worldMatrix is the world matrix of the particle system
  56577. * @param directionToUpdate is the direction vector to update with the result
  56578. * @param particle is the particle we are computed the direction for
  56579. */
  56580. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56581. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56582. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56583. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56584. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56585. };
  56586. /**
  56587. * Called by the particle System when the position is computed for the created particle.
  56588. * @param worldMatrix is the world matrix of the particle system
  56589. * @param positionToUpdate is the position vector to update with the result
  56590. * @param particle is the particle we are computed the position for
  56591. */
  56592. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56593. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56594. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56595. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56596. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56597. };
  56598. /**
  56599. * Clones the current emitter and returns a copy of it
  56600. * @returns the new emitter
  56601. */
  56602. BoxParticleEmitter.prototype.clone = function () {
  56603. var newOne = new BoxParticleEmitter();
  56604. BABYLON.Tools.DeepCopy(this, newOne);
  56605. return newOne;
  56606. };
  56607. /**
  56608. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56609. * @param effect defines the update shader
  56610. */
  56611. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56612. effect.setVector3("direction1", this.direction1);
  56613. effect.setVector3("direction2", this.direction2);
  56614. effect.setVector3("minEmitBox", this.minEmitBox);
  56615. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56616. };
  56617. /**
  56618. * Returns a string to use to update the GPU particles update shader
  56619. * @returns a string containng the defines string
  56620. */
  56621. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56622. return "#define BOXEMITTER";
  56623. };
  56624. /**
  56625. * Returns the string "BoxEmitter"
  56626. * @returns a string containing the class name
  56627. */
  56628. BoxParticleEmitter.prototype.getClassName = function () {
  56629. return "BoxEmitter";
  56630. };
  56631. /**
  56632. * Serializes the particle system to a JSON object.
  56633. * @returns the JSON object
  56634. */
  56635. BoxParticleEmitter.prototype.serialize = function () {
  56636. var serializationObject = {};
  56637. serializationObject.type = this.getClassName();
  56638. serializationObject.direction1 = this.direction1.asArray();
  56639. ;
  56640. serializationObject.direction2 = this.direction2.asArray();
  56641. ;
  56642. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56643. ;
  56644. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56645. ;
  56646. return serializationObject;
  56647. };
  56648. /**
  56649. * Parse properties from a JSON object
  56650. * @param serializationObject defines the JSON object
  56651. */
  56652. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56653. this.direction1.copyFrom(serializationObject.direction1);
  56654. this.direction2.copyFrom(serializationObject.direction2);
  56655. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56656. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56657. };
  56658. return BoxParticleEmitter;
  56659. }());
  56660. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56661. })(BABYLON || (BABYLON = {}));
  56662. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56663. var BABYLON;
  56664. (function (BABYLON) {
  56665. /**
  56666. * Particle emitter emitting particles from the inside of a cone.
  56667. * It emits the particles alongside the cone volume from the base to the particle.
  56668. * The emission direction might be randomized.
  56669. */
  56670. var ConeParticleEmitter = /** @class */ (function () {
  56671. /**
  56672. * Creates a new instance ConeParticleEmitter
  56673. * @param radius the radius of the emission cone (1 by default)
  56674. * @param angles the cone base angle (PI by default)
  56675. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56676. */
  56677. function ConeParticleEmitter(radius,
  56678. /**
  56679. * The radius of the emission cone.
  56680. */
  56681. angle,
  56682. /**
  56683. * The cone base angle.
  56684. */
  56685. directionRandomizer) {
  56686. if (radius === void 0) { radius = 1; }
  56687. if (angle === void 0) { angle = Math.PI; }
  56688. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56689. this.angle = angle;
  56690. this.directionRandomizer = directionRandomizer;
  56691. this.radius = radius;
  56692. }
  56693. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56694. /**
  56695. * Gets the radius of the emission cone.
  56696. */
  56697. get: function () {
  56698. return this._radius;
  56699. },
  56700. /**
  56701. * Sets the radius of the emission cone.
  56702. */
  56703. set: function (value) {
  56704. this._radius = value;
  56705. if (this.angle !== 0) {
  56706. this._height = value / Math.tan(this.angle / 2);
  56707. }
  56708. else {
  56709. this._height = 1;
  56710. }
  56711. },
  56712. enumerable: true,
  56713. configurable: true
  56714. });
  56715. /**
  56716. * Called by the particle System when the direction is computed for the created particle.
  56717. * @param emitPower is the power of the particle (speed)
  56718. * @param worldMatrix is the world matrix of the particle system
  56719. * @param directionToUpdate is the direction vector to update with the result
  56720. * @param particle is the particle we are computed the direction for
  56721. */
  56722. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56723. if (this.angle === 0) {
  56724. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56725. }
  56726. else {
  56727. // measure the direction Vector from the emitter to the particle.
  56728. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56729. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56730. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56731. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56732. direction.x += randX;
  56733. direction.y += randY;
  56734. direction.z += randZ;
  56735. direction.normalize();
  56736. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56737. }
  56738. };
  56739. /**
  56740. * Called by the particle System when the position is computed for the created particle.
  56741. * @param worldMatrix is the world matrix of the particle system
  56742. * @param positionToUpdate is the position vector to update with the result
  56743. * @param particle is the particle we are computed the position for
  56744. */
  56745. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56746. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56747. var h = BABYLON.Scalar.RandomRange(0, 1);
  56748. // Better distribution in a cone at normal angles.
  56749. h = 1 - h * h;
  56750. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56751. radius = radius * h;
  56752. var randX = radius * Math.sin(s);
  56753. var randZ = radius * Math.cos(s);
  56754. var randY = h * this._height;
  56755. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56756. };
  56757. /**
  56758. * Clones the current emitter and returns a copy of it
  56759. * @returns the new emitter
  56760. */
  56761. ConeParticleEmitter.prototype.clone = function () {
  56762. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56763. BABYLON.Tools.DeepCopy(this, newOne);
  56764. return newOne;
  56765. };
  56766. /**
  56767. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56768. * @param effect defines the update shader
  56769. */
  56770. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56771. effect.setFloat("radius", this.radius);
  56772. effect.setFloat("angle", this.angle);
  56773. effect.setFloat("height", this._height);
  56774. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56775. };
  56776. /**
  56777. * Returns a string to use to update the GPU particles update shader
  56778. * @returns a string containng the defines string
  56779. */
  56780. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56781. return "#define CONEEMITTER";
  56782. };
  56783. /**
  56784. * Returns the string "BoxEmitter"
  56785. * @returns a string containing the class name
  56786. */
  56787. ConeParticleEmitter.prototype.getClassName = function () {
  56788. return "ConeEmitter";
  56789. };
  56790. /**
  56791. * Serializes the particle system to a JSON object.
  56792. * @returns the JSON object
  56793. */
  56794. ConeParticleEmitter.prototype.serialize = function () {
  56795. var serializationObject = {};
  56796. serializationObject.type = this.getClassName();
  56797. serializationObject.radius = this.radius;
  56798. serializationObject.angle = this.angle;
  56799. serializationObject.directionRandomizer = this.directionRandomizer;
  56800. return serializationObject;
  56801. };
  56802. /**
  56803. * Parse properties from a JSON object
  56804. * @param serializationObject defines the JSON object
  56805. */
  56806. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56807. this.radius = serializationObject.radius;
  56808. this.angle = serializationObject.angle;
  56809. this.directionRandomizer = serializationObject.directionRandomizer;
  56810. };
  56811. return ConeParticleEmitter;
  56812. }());
  56813. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56814. })(BABYLON || (BABYLON = {}));
  56815. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56816. var BABYLON;
  56817. (function (BABYLON) {
  56818. /**
  56819. * Particle emitter emitting particles from the inside of a sphere.
  56820. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56821. */
  56822. var SphereParticleEmitter = /** @class */ (function () {
  56823. /**
  56824. * Creates a new instance SphereParticleEmitter
  56825. * @param radius the radius of the emission sphere (1 by default)
  56826. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56827. */
  56828. function SphereParticleEmitter(
  56829. /**
  56830. * The radius of the emission sphere.
  56831. */
  56832. radius,
  56833. /**
  56834. * How much to randomize the particle direction [0-1].
  56835. */
  56836. directionRandomizer) {
  56837. if (radius === void 0) { radius = 1; }
  56838. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56839. this.radius = radius;
  56840. this.directionRandomizer = directionRandomizer;
  56841. }
  56842. /**
  56843. * Called by the particle System when the direction is computed for the created particle.
  56844. * @param emitPower is the power of the particle (speed)
  56845. * @param worldMatrix is the world matrix of the particle system
  56846. * @param directionToUpdate is the direction vector to update with the result
  56847. * @param particle is the particle we are computed the direction for
  56848. */
  56849. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56850. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56851. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56852. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56853. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56854. direction.x += randX;
  56855. direction.y += randY;
  56856. direction.z += randZ;
  56857. direction.normalize();
  56858. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56859. };
  56860. /**
  56861. * Called by the particle System when the position is computed for the created particle.
  56862. * @param worldMatrix is the world matrix of the particle system
  56863. * @param positionToUpdate is the position vector to update with the result
  56864. * @param particle is the particle we are computed the position for
  56865. */
  56866. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56867. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56868. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56869. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56870. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56871. var randY = randRadius * Math.cos(theta);
  56872. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56873. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56874. };
  56875. /**
  56876. * Clones the current emitter and returns a copy of it
  56877. * @returns the new emitter
  56878. */
  56879. SphereParticleEmitter.prototype.clone = function () {
  56880. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56881. BABYLON.Tools.DeepCopy(this, newOne);
  56882. return newOne;
  56883. };
  56884. /**
  56885. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56886. * @param effect defines the update shader
  56887. */
  56888. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56889. effect.setFloat("radius", this.radius);
  56890. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56891. };
  56892. /**
  56893. * Returns a string to use to update the GPU particles update shader
  56894. * @returns a string containng the defines string
  56895. */
  56896. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56897. return "#define SPHEREEMITTER";
  56898. };
  56899. /**
  56900. * Returns the string "SphereParticleEmitter"
  56901. * @returns a string containing the class name
  56902. */
  56903. SphereParticleEmitter.prototype.getClassName = function () {
  56904. return "SphereParticleEmitter";
  56905. };
  56906. /**
  56907. * Serializes the particle system to a JSON object.
  56908. * @returns the JSON object
  56909. */
  56910. SphereParticleEmitter.prototype.serialize = function () {
  56911. var serializationObject = {};
  56912. serializationObject.type = this.getClassName();
  56913. serializationObject.radius = this.radius;
  56914. serializationObject.directionRandomizer = this.directionRandomizer;
  56915. return serializationObject;
  56916. };
  56917. /**
  56918. * Parse properties from a JSON object
  56919. * @param serializationObject defines the JSON object
  56920. */
  56921. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56922. this.radius = serializationObject.radius;
  56923. this.directionRandomizer = serializationObject.directionRandomizer;
  56924. };
  56925. return SphereParticleEmitter;
  56926. }());
  56927. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56928. /**
  56929. * Particle emitter emitting particles from the inside of a sphere.
  56930. * It emits the particles randomly between two vectors.
  56931. */
  56932. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56933. __extends(SphereDirectedParticleEmitter, _super);
  56934. /**
  56935. * Creates a new instance SphereDirectedParticleEmitter
  56936. * @param radius the radius of the emission sphere (1 by default)
  56937. * @param direction1 the min limit of the emission direction (up vector by default)
  56938. * @param direction2 the max limit of the emission direction (up vector by default)
  56939. */
  56940. function SphereDirectedParticleEmitter(radius,
  56941. /**
  56942. * The min limit of the emission direction.
  56943. */
  56944. direction1,
  56945. /**
  56946. * The max limit of the emission direction.
  56947. */
  56948. direction2) {
  56949. if (radius === void 0) { radius = 1; }
  56950. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56951. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56952. var _this = _super.call(this, radius) || this;
  56953. _this.direction1 = direction1;
  56954. _this.direction2 = direction2;
  56955. return _this;
  56956. }
  56957. /**
  56958. * Called by the particle System when the direction is computed for the created particle.
  56959. * @param emitPower is the power of the particle (speed)
  56960. * @param worldMatrix is the world matrix of the particle system
  56961. * @param directionToUpdate is the direction vector to update with the result
  56962. * @param particle is the particle we are computed the direction for
  56963. */
  56964. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56965. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56966. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56967. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56968. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56969. };
  56970. /**
  56971. * Clones the current emitter and returns a copy of it
  56972. * @returns the new emitter
  56973. */
  56974. SphereDirectedParticleEmitter.prototype.clone = function () {
  56975. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56976. BABYLON.Tools.DeepCopy(this, newOne);
  56977. return newOne;
  56978. };
  56979. /**
  56980. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56981. * @param effect defines the update shader
  56982. */
  56983. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56984. effect.setFloat("radius", this.radius);
  56985. effect.setVector3("direction1", this.direction1);
  56986. effect.setVector3("direction2", this.direction2);
  56987. };
  56988. /**
  56989. * Returns a string to use to update the GPU particles update shader
  56990. * @returns a string containng the defines string
  56991. */
  56992. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56993. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56994. };
  56995. /**
  56996. * Returns the string "SphereDirectedParticleEmitter"
  56997. * @returns a string containing the class name
  56998. */
  56999. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57000. return "SphereDirectedParticleEmitter";
  57001. };
  57002. /**
  57003. * Serializes the particle system to a JSON object.
  57004. * @returns the JSON object
  57005. */
  57006. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57007. var serializationObject = _super.prototype.serialize.call(this);
  57008. ;
  57009. serializationObject.direction1 = this.direction1.asArray();
  57010. ;
  57011. serializationObject.direction2 = this.direction2.asArray();
  57012. ;
  57013. return serializationObject;
  57014. };
  57015. /**
  57016. * Parse properties from a JSON object
  57017. * @param serializationObject defines the JSON object
  57018. */
  57019. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57020. _super.prototype.parse.call(this, serializationObject);
  57021. this.direction1.copyFrom(serializationObject.direction1);
  57022. this.direction2.copyFrom(serializationObject.direction2);
  57023. };
  57024. return SphereDirectedParticleEmitter;
  57025. }(SphereParticleEmitter));
  57026. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57027. })(BABYLON || (BABYLON = {}));
  57028. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57029. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57030. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57031. s = arguments[i];
  57032. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57033. t[p] = s[p];
  57034. }
  57035. return t;
  57036. };
  57037. var BABYLON;
  57038. (function (BABYLON) {
  57039. /**
  57040. * This represents a GPU particle system in Babylon
  57041. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57042. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57043. */
  57044. var GPUParticleSystem = /** @class */ (function () {
  57045. /**
  57046. * Instantiates a GPU particle system.
  57047. * 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.
  57048. * @param name The name of the particle system
  57049. * @param capacity The max number of particles alive at the same time
  57050. * @param scene The scene the particle system belongs to
  57051. */
  57052. function GPUParticleSystem(name, options, scene) {
  57053. /**
  57054. * The emitter represents the Mesh or position we are attaching the particle system to.
  57055. */
  57056. this.emitter = null;
  57057. /**
  57058. * The rendering group used by the Particle system to chose when to render.
  57059. */
  57060. this.renderingGroupId = 0;
  57061. /**
  57062. * The layer mask we are rendering the particles through.
  57063. */
  57064. this.layerMask = 0x0FFFFFFF;
  57065. this._targetIndex = 0;
  57066. this._currentRenderId = -1;
  57067. this._started = false;
  57068. this._stopped = false;
  57069. this._timeDelta = 0;
  57070. this._attributesStrideSize = 14;
  57071. this._actualFrame = 0;
  57072. /**
  57073. * List of animations used by the particle system.
  57074. */
  57075. this.animations = [];
  57076. /**
  57077. * An event triggered when the system is disposed.
  57078. */
  57079. this.onDisposeObservable = new BABYLON.Observable();
  57080. /**
  57081. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57082. */
  57083. this.updateSpeed = 0.01;
  57084. /**
  57085. * The amount of time the particle system is running (depends of the overall update speed).
  57086. */
  57087. this.targetStopDuration = 0;
  57088. /**
  57089. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57090. */
  57091. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57092. /**
  57093. * Minimum life time of emitting particles.
  57094. */
  57095. this.minLifeTime = 1;
  57096. /**
  57097. * Maximum life time of emitting particles.
  57098. */
  57099. this.maxLifeTime = 1;
  57100. /**
  57101. * Minimum Size of emitting particles.
  57102. */
  57103. this.minSize = 1;
  57104. /**
  57105. * Maximum Size of emitting particles.
  57106. */
  57107. this.maxSize = 1;
  57108. /**
  57109. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57110. */
  57111. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57112. /**
  57113. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57114. */
  57115. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57116. /**
  57117. * Color the particle will have at the end of its lifetime.
  57118. */
  57119. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57120. /**
  57121. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57122. */
  57123. this.emitRate = 100;
  57124. /**
  57125. * You can use gravity if you want to give an orientation to your particles.
  57126. */
  57127. this.gravity = BABYLON.Vector3.Zero();
  57128. /**
  57129. * Minimum power of emitting particles.
  57130. */
  57131. this.minEmitPower = 1;
  57132. /**
  57133. * Maximum power of emitting particles.
  57134. */
  57135. this.maxEmitPower = 1;
  57136. /**
  57137. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57138. * to override the particles.
  57139. */
  57140. this.forceDepthWrite = false;
  57141. this.id = name;
  57142. this.name = name;
  57143. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57144. this._engine = this._scene.getEngine();
  57145. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57146. this._capacity = fullOptions.capacity;
  57147. this._activeCount = fullOptions.capacity;
  57148. this._currentActiveCount = 0;
  57149. this._scene.particleSystems.push(this);
  57150. this._updateEffectOptions = {
  57151. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57152. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57153. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57154. uniformBuffersNames: [],
  57155. samplers: ["randomSampler"],
  57156. defines: "",
  57157. fallbacks: null,
  57158. onCompiled: null,
  57159. onError: null,
  57160. indexParameters: null,
  57161. maxSimultaneousLights: 0,
  57162. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57163. };
  57164. // Random data
  57165. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57166. var d = [];
  57167. for (var i = 0; i < maxTextureSize; ++i) {
  57168. d.push(Math.random());
  57169. d.push(Math.random());
  57170. d.push(Math.random());
  57171. d.push(Math.random());
  57172. }
  57173. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57174. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57175. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57176. this._randomTextureSize = maxTextureSize;
  57177. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57178. }
  57179. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57180. /**
  57181. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57182. */
  57183. get: function () {
  57184. if (!BABYLON.Engine.LastCreatedEngine) {
  57185. return false;
  57186. }
  57187. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57188. },
  57189. enumerable: true,
  57190. configurable: true
  57191. });
  57192. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57193. /**
  57194. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57195. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57196. */
  57197. get: function () {
  57198. if (this.particleEmitterType.direction1) {
  57199. return this.particleEmitterType.direction1;
  57200. }
  57201. return BABYLON.Vector3.Zero();
  57202. },
  57203. set: function (value) {
  57204. if (this.particleEmitterType.direction1) {
  57205. this.particleEmitterType.direction1 = value;
  57206. }
  57207. },
  57208. enumerable: true,
  57209. configurable: true
  57210. });
  57211. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57212. /**
  57213. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57214. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57215. */
  57216. get: function () {
  57217. if (this.particleEmitterType.direction2) {
  57218. return this.particleEmitterType.direction2;
  57219. }
  57220. return BABYLON.Vector3.Zero();
  57221. },
  57222. set: function (value) {
  57223. if (this.particleEmitterType.direction2) {
  57224. this.particleEmitterType.direction2 = value;
  57225. }
  57226. },
  57227. enumerable: true,
  57228. configurable: true
  57229. });
  57230. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57231. /**
  57232. * 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.
  57233. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57234. */
  57235. get: function () {
  57236. if (this.particleEmitterType.minEmitBox) {
  57237. return this.particleEmitterType.minEmitBox;
  57238. }
  57239. return BABYLON.Vector3.Zero();
  57240. },
  57241. set: function (value) {
  57242. if (this.particleEmitterType.minEmitBox) {
  57243. this.particleEmitterType.minEmitBox = value;
  57244. }
  57245. },
  57246. enumerable: true,
  57247. configurable: true
  57248. });
  57249. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57250. /**
  57251. * 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.
  57252. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57253. */
  57254. get: function () {
  57255. if (this.particleEmitterType.maxEmitBox) {
  57256. return this.particleEmitterType.maxEmitBox;
  57257. }
  57258. return BABYLON.Vector3.Zero();
  57259. },
  57260. set: function (value) {
  57261. if (this.particleEmitterType.maxEmitBox) {
  57262. this.particleEmitterType.maxEmitBox = value;
  57263. }
  57264. },
  57265. enumerable: true,
  57266. configurable: true
  57267. });
  57268. /**
  57269. * Gets the maximum number of particles active at the same time.
  57270. * @returns The max number of active particles.
  57271. */
  57272. GPUParticleSystem.prototype.getCapacity = function () {
  57273. return this._capacity;
  57274. };
  57275. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57276. /**
  57277. * Gets or set the number of active particles
  57278. */
  57279. get: function () {
  57280. return this._activeCount;
  57281. },
  57282. set: function (value) {
  57283. this._activeCount = Math.min(value, this._capacity);
  57284. },
  57285. enumerable: true,
  57286. configurable: true
  57287. });
  57288. /**
  57289. * Is this system ready to be used/rendered
  57290. * @return true if the system is ready
  57291. */
  57292. GPUParticleSystem.prototype.isReady = function () {
  57293. if (!this._updateEffect) {
  57294. this._recreateUpdateEffect();
  57295. this._recreateRenderEffect();
  57296. return false;
  57297. }
  57298. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57299. return false;
  57300. }
  57301. return true;
  57302. };
  57303. /**
  57304. * Gets Wether the system has been started.
  57305. * @returns True if it has been started, otherwise false.
  57306. */
  57307. GPUParticleSystem.prototype.isStarted = function () {
  57308. return this._started;
  57309. };
  57310. /**
  57311. * Starts the particle system and begins to emit.
  57312. */
  57313. GPUParticleSystem.prototype.start = function () {
  57314. this._started = true;
  57315. this._stopped = false;
  57316. };
  57317. /**
  57318. * Stops the particle system.
  57319. */
  57320. GPUParticleSystem.prototype.stop = function () {
  57321. this._stopped = true;
  57322. };
  57323. /**
  57324. * Remove all active particles
  57325. */
  57326. GPUParticleSystem.prototype.reset = function () {
  57327. this._releaseBuffers();
  57328. this._releaseVAOs();
  57329. this._currentActiveCount = 0;
  57330. this._targetIndex = 0;
  57331. };
  57332. /**
  57333. * Returns the string "GPUParticleSystem"
  57334. * @returns a string containing the class name
  57335. */
  57336. GPUParticleSystem.prototype.getClassName = function () {
  57337. return "GPUParticleSystem";
  57338. };
  57339. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57340. var updateVertexBuffers = {};
  57341. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57342. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57343. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57344. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57345. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57346. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57347. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57348. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57349. this._engine.bindArrayBuffer(null);
  57350. return vao;
  57351. };
  57352. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57353. var renderVertexBuffers = {};
  57354. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57355. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57356. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57357. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57358. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57359. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57360. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57361. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57362. this._engine.bindArrayBuffer(null);
  57363. return vao;
  57364. };
  57365. GPUParticleSystem.prototype._initialize = function (force) {
  57366. if (force === void 0) { force = false; }
  57367. if (this._buffer0 && !force) {
  57368. return;
  57369. }
  57370. var engine = this._scene.getEngine();
  57371. var data = new Array();
  57372. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57373. // position
  57374. data.push(0.0);
  57375. data.push(0.0);
  57376. data.push(0.0);
  57377. // Age and life
  57378. data.push(0.0); // create the particle as a dead one to create a new one at start
  57379. data.push(0.0);
  57380. // Seed
  57381. data.push(Math.random());
  57382. // Size
  57383. data.push(0.0);
  57384. // color
  57385. data.push(0.0);
  57386. data.push(0.0);
  57387. data.push(0.0);
  57388. data.push(0.0);
  57389. // direction
  57390. data.push(0.0);
  57391. data.push(0.0);
  57392. data.push(0.0);
  57393. }
  57394. // Sprite data
  57395. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57396. -0.5, 0.5, 0, 1,
  57397. -0.5, -0.5, 0, 0,
  57398. 0.5, -0.5, 1, 0]);
  57399. // Buffers
  57400. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57401. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57402. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57403. // Update VAO
  57404. this._updateVAO = [];
  57405. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57406. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57407. // Render VAO
  57408. this._renderVAO = [];
  57409. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57410. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57411. // Links
  57412. this._sourceBuffer = this._buffer0;
  57413. this._targetBuffer = this._buffer1;
  57414. };
  57415. /** @hidden */
  57416. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57417. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57418. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57419. return;
  57420. }
  57421. this._updateEffectOptions.defines = defines;
  57422. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57423. };
  57424. /** @hidden */
  57425. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57426. var defines = "";
  57427. if (this._scene.clipPlane) {
  57428. defines = "\n#define CLIPPLANE";
  57429. }
  57430. if (this._renderEffect && this._renderEffect.defines === defines) {
  57431. return;
  57432. }
  57433. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57434. };
  57435. /**
  57436. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57437. */
  57438. GPUParticleSystem.prototype.animate = function () {
  57439. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57440. this._actualFrame += this._timeDelta;
  57441. if (!this._stopped) {
  57442. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57443. this.stop();
  57444. }
  57445. }
  57446. };
  57447. /**
  57448. * Renders the particle system in its current state.
  57449. * @returns the current number of particles
  57450. */
  57451. GPUParticleSystem.prototype.render = function () {
  57452. if (!this._started) {
  57453. return 0;
  57454. }
  57455. this._recreateUpdateEffect();
  57456. this._recreateRenderEffect();
  57457. if (!this.isReady()) {
  57458. return 0;
  57459. }
  57460. if (this._currentRenderId === this._scene.getRenderId()) {
  57461. return 0;
  57462. }
  57463. this._currentRenderId = this._scene.getRenderId();
  57464. // Get everything ready to render
  57465. this._initialize();
  57466. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57467. // Enable update effect
  57468. this._engine.enableEffect(this._updateEffect);
  57469. this._engine.setState(false);
  57470. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57471. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57472. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57473. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57474. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57475. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57476. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57477. this._updateEffect.setDirectColor4("color1", this.color1);
  57478. this._updateEffect.setDirectColor4("color2", this.color2);
  57479. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57480. this._updateEffect.setVector3("gravity", this.gravity);
  57481. if (this.particleEmitterType) {
  57482. this.particleEmitterType.applyToShader(this._updateEffect);
  57483. }
  57484. var emitterWM;
  57485. if (this.emitter.position) {
  57486. var emitterMesh = this.emitter;
  57487. emitterWM = emitterMesh.getWorldMatrix();
  57488. }
  57489. else {
  57490. var emitterPosition = this.emitter;
  57491. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57492. }
  57493. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57494. // Bind source VAO
  57495. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57496. // Update
  57497. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57498. this._engine.setRasterizerState(false);
  57499. this._engine.beginTransformFeedback();
  57500. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57501. this._engine.endTransformFeedback();
  57502. this._engine.setRasterizerState(true);
  57503. this._engine.bindTransformFeedbackBuffer(null);
  57504. // Enable render effect
  57505. this._engine.enableEffect(this._renderEffect);
  57506. var viewMatrix = this._scene.getViewMatrix();
  57507. this._renderEffect.setMatrix("view", viewMatrix);
  57508. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57509. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57510. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57511. if (this._scene.clipPlane) {
  57512. var clipPlane = this._scene.clipPlane;
  57513. var invView = viewMatrix.clone();
  57514. invView.invert();
  57515. this._renderEffect.setMatrix("invView", invView);
  57516. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57517. }
  57518. // Draw order
  57519. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57520. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57521. }
  57522. else {
  57523. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57524. }
  57525. if (this.forceDepthWrite) {
  57526. this._engine.setDepthWrite(true);
  57527. }
  57528. // Bind source VAO
  57529. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57530. // Render
  57531. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57532. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57533. // Switch VAOs
  57534. this._targetIndex++;
  57535. if (this._targetIndex === 2) {
  57536. this._targetIndex = 0;
  57537. }
  57538. // Switch buffers
  57539. var tmpBuffer = this._sourceBuffer;
  57540. this._sourceBuffer = this._targetBuffer;
  57541. this._targetBuffer = tmpBuffer;
  57542. return this._currentActiveCount;
  57543. };
  57544. /**
  57545. * Rebuilds the particle system
  57546. */
  57547. GPUParticleSystem.prototype.rebuild = function () {
  57548. this._initialize(true);
  57549. };
  57550. GPUParticleSystem.prototype._releaseBuffers = function () {
  57551. if (this._buffer0) {
  57552. this._buffer0.dispose();
  57553. this._buffer0 = null;
  57554. }
  57555. if (this._buffer1) {
  57556. this._buffer1.dispose();
  57557. this._buffer1 = null;
  57558. }
  57559. if (this._spriteBuffer) {
  57560. this._spriteBuffer.dispose();
  57561. this._spriteBuffer = null;
  57562. }
  57563. };
  57564. GPUParticleSystem.prototype._releaseVAOs = function () {
  57565. if (!this._updateVAO) {
  57566. return;
  57567. }
  57568. for (var index = 0; index < this._updateVAO.length; index++) {
  57569. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57570. }
  57571. this._updateVAO = [];
  57572. for (var index = 0; index < this._renderVAO.length; index++) {
  57573. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57574. }
  57575. this._renderVAO = [];
  57576. };
  57577. /**
  57578. * Disposes the particle system and free the associated resources
  57579. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57580. */
  57581. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57582. if (disposeTexture === void 0) { disposeTexture = true; }
  57583. var index = this._scene.particleSystems.indexOf(this);
  57584. if (index > -1) {
  57585. this._scene.particleSystems.splice(index, 1);
  57586. }
  57587. this._releaseBuffers();
  57588. this._releaseVAOs();
  57589. if (this._randomTexture) {
  57590. this._randomTexture.dispose();
  57591. this._randomTexture = null;
  57592. }
  57593. if (disposeTexture && this.particleTexture) {
  57594. this.particleTexture.dispose();
  57595. this.particleTexture = null;
  57596. }
  57597. // Callback
  57598. this.onDisposeObservable.notifyObservers(this);
  57599. this.onDisposeObservable.clear();
  57600. };
  57601. /**
  57602. * Clones the particle system.
  57603. * @param name The name of the cloned object
  57604. * @param newEmitter The new emitter to use
  57605. * @returns the cloned particle system
  57606. */
  57607. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57608. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57609. BABYLON.Tools.DeepCopy(this, result);
  57610. if (newEmitter === undefined) {
  57611. newEmitter = this.emitter;
  57612. }
  57613. result.emitter = newEmitter;
  57614. if (this.particleTexture) {
  57615. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57616. }
  57617. return result;
  57618. };
  57619. /**
  57620. * Serializes the particle system to a JSON object.
  57621. * @returns the JSON object
  57622. */
  57623. GPUParticleSystem.prototype.serialize = function () {
  57624. var serializationObject = {};
  57625. serializationObject.name = this.name;
  57626. serializationObject.id = this.id;
  57627. // Emitter
  57628. if (this.emitter.position) {
  57629. var emitterMesh = this.emitter;
  57630. serializationObject.emitterId = emitterMesh.id;
  57631. }
  57632. else {
  57633. var emitterPosition = this.emitter;
  57634. serializationObject.emitter = emitterPosition.asArray();
  57635. }
  57636. serializationObject.capacity = this.getCapacity();
  57637. if (this.particleTexture) {
  57638. serializationObject.textureName = this.particleTexture.name;
  57639. }
  57640. // Animations
  57641. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57642. // Particle system
  57643. serializationObject.activeParticleCount = this.activeParticleCount;
  57644. serializationObject.randomTextureSize = this._randomTextureSize;
  57645. serializationObject.minSize = this.minSize;
  57646. serializationObject.maxSize = this.maxSize;
  57647. serializationObject.minEmitPower = this.minEmitPower;
  57648. serializationObject.maxEmitPower = this.maxEmitPower;
  57649. serializationObject.minLifeTime = this.minLifeTime;
  57650. serializationObject.maxLifeTime = this.maxLifeTime;
  57651. serializationObject.emitRate = this.emitRate;
  57652. serializationObject.gravity = this.gravity.asArray();
  57653. serializationObject.color1 = this.color1.asArray();
  57654. serializationObject.color2 = this.color2.asArray();
  57655. serializationObject.colorDead = this.colorDead.asArray();
  57656. serializationObject.updateSpeed = this.updateSpeed;
  57657. serializationObject.targetStopDuration = this.targetStopDuration;
  57658. serializationObject.blendMode = this.blendMode;
  57659. // Emitter
  57660. if (this.particleEmitterType) {
  57661. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57662. }
  57663. return serializationObject;
  57664. };
  57665. /**
  57666. * Parses a JSON object to create a GPU particle system.
  57667. * @param parsedParticleSystem The JSON object to parse
  57668. * @param scene The scene to create the particle system in
  57669. * @param rootUrl The root url to use to load external dependencies like texture
  57670. * @returns the parsed GPU particle system
  57671. */
  57672. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57673. var name = parsedParticleSystem.name;
  57674. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57675. if (parsedParticleSystem.id) {
  57676. particleSystem.id = parsedParticleSystem.id;
  57677. }
  57678. // Texture
  57679. if (parsedParticleSystem.textureName) {
  57680. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57681. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57682. }
  57683. // Emitter
  57684. if (parsedParticleSystem.emitterId) {
  57685. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57686. }
  57687. else {
  57688. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57689. }
  57690. // Animations
  57691. if (parsedParticleSystem.animations) {
  57692. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57693. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57694. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57695. }
  57696. }
  57697. // Particle system
  57698. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57699. particleSystem.minSize = parsedParticleSystem.minSize;
  57700. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57701. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57702. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57703. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57704. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57705. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57706. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57707. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57708. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57709. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57710. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57711. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57712. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57713. // Emitter
  57714. if (parsedParticleSystem.particleEmitterType) {
  57715. var emitterType = void 0;
  57716. switch (parsedParticleSystem.particleEmitterType.type) {
  57717. case "SphereEmitter":
  57718. emitterType = new BABYLON.SphereParticleEmitter();
  57719. break;
  57720. case "SphereDirectedParticleEmitter":
  57721. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57722. break;
  57723. case "ConeEmitter":
  57724. emitterType = new BABYLON.ConeParticleEmitter();
  57725. break;
  57726. case "BoxEmitter":
  57727. default:
  57728. emitterType = new BABYLON.BoxParticleEmitter();
  57729. break;
  57730. }
  57731. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57732. particleSystem.particleEmitterType = emitterType;
  57733. }
  57734. return particleSystem;
  57735. };
  57736. return GPUParticleSystem;
  57737. }());
  57738. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57739. })(BABYLON || (BABYLON = {}));
  57740. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57741. var BABYLON;
  57742. (function (BABYLON) {
  57743. /**
  57744. * Represents one particle of a solid particle system.
  57745. */
  57746. var SolidParticle = /** @class */ (function () {
  57747. /**
  57748. * Creates a Solid Particle object.
  57749. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57750. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57751. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57752. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57753. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57754. * @param shapeId (integer) is the model shape identifier in the SPS.
  57755. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57756. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57757. */
  57758. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57759. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57760. /**
  57761. * particle global index
  57762. */
  57763. this.idx = 0;
  57764. /**
  57765. * The color of the particle
  57766. */
  57767. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57768. /**
  57769. * The world space position of the particle.
  57770. */
  57771. this.position = BABYLON.Vector3.Zero();
  57772. /**
  57773. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57774. */
  57775. this.rotation = BABYLON.Vector3.Zero();
  57776. /**
  57777. * The scaling of the particle.
  57778. */
  57779. this.scaling = BABYLON.Vector3.One();
  57780. /**
  57781. * The uvs of the particle.
  57782. */
  57783. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57784. /**
  57785. * The current speed of the particle.
  57786. */
  57787. this.velocity = BABYLON.Vector3.Zero();
  57788. /**
  57789. * The pivot point in the particle local space.
  57790. */
  57791. this.pivot = BABYLON.Vector3.Zero();
  57792. /**
  57793. * Must the particle be translated from its pivot point in its local space ?
  57794. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57795. * Default : false
  57796. */
  57797. this.translateFromPivot = false;
  57798. /**
  57799. * Is the particle active or not ?
  57800. */
  57801. this.alive = true;
  57802. /**
  57803. * Is the particle visible or not ?
  57804. */
  57805. this.isVisible = true;
  57806. /**
  57807. * Index of this particle in the global "positions" array (Internal use)
  57808. */
  57809. this._pos = 0;
  57810. /**
  57811. * Index of this particle in the global "indices" array (Internal use)
  57812. */
  57813. this._ind = 0;
  57814. /**
  57815. * ModelShape id of this particle
  57816. */
  57817. this.shapeId = 0;
  57818. /**
  57819. * Index of the particle in its shape id (Internal use)
  57820. */
  57821. this.idxInShape = 0;
  57822. /**
  57823. * Still set as invisible in order to skip useless computations (Internal use)
  57824. */
  57825. this._stillInvisible = false;
  57826. /**
  57827. * Last computed particle rotation matrix
  57828. */
  57829. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57830. /**
  57831. * Parent particle Id, if any.
  57832. * Default null.
  57833. */
  57834. this.parentId = null;
  57835. /**
  57836. * Internal global position in the SPS.
  57837. */
  57838. this._globalPosition = BABYLON.Vector3.Zero();
  57839. this.idx = particleIndex;
  57840. this._pos = positionIndex;
  57841. this._ind = indiceIndex;
  57842. this._model = model;
  57843. this.shapeId = shapeId;
  57844. this.idxInShape = idxInShape;
  57845. this._sps = sps;
  57846. if (modelBoundingInfo) {
  57847. this._modelBoundingInfo = modelBoundingInfo;
  57848. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57849. }
  57850. }
  57851. Object.defineProperty(SolidParticle.prototype, "scale", {
  57852. /**
  57853. * Legacy support, changed scale to scaling
  57854. */
  57855. get: function () {
  57856. return this.scaling;
  57857. },
  57858. /**
  57859. * Legacy support, changed scale to scaling
  57860. */
  57861. set: function (scale) {
  57862. this.scaling = scale;
  57863. },
  57864. enumerable: true,
  57865. configurable: true
  57866. });
  57867. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57868. /**
  57869. * Legacy support, changed quaternion to rotationQuaternion
  57870. */
  57871. get: function () {
  57872. return this.rotationQuaternion;
  57873. },
  57874. /**
  57875. * Legacy support, changed quaternion to rotationQuaternion
  57876. */
  57877. set: function (q) {
  57878. this.rotationQuaternion = q;
  57879. },
  57880. enumerable: true,
  57881. configurable: true
  57882. });
  57883. /**
  57884. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57885. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57886. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57887. * @returns true if it intersects
  57888. */
  57889. SolidParticle.prototype.intersectsMesh = function (target) {
  57890. if (!this._boundingInfo || !target._boundingInfo) {
  57891. return false;
  57892. }
  57893. if (this._sps._bSphereOnly) {
  57894. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57895. }
  57896. return this._boundingInfo.intersects(target._boundingInfo, false);
  57897. };
  57898. return SolidParticle;
  57899. }());
  57900. BABYLON.SolidParticle = SolidParticle;
  57901. /**
  57902. * Represents the shape of the model used by one particle of a solid particle system.
  57903. * SPS internal tool, don't use it manually.
  57904. */
  57905. var ModelShape = /** @class */ (function () {
  57906. /**
  57907. * 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.
  57908. * SPS internal tool, don't use it manually.
  57909. * @hidden
  57910. */
  57911. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57912. /**
  57913. * length of the shape in the model indices array (internal use)
  57914. */
  57915. this._indicesLength = 0;
  57916. this.shapeID = id;
  57917. this._shape = shape;
  57918. this._indicesLength = indicesLength;
  57919. this._shapeUV = shapeUV;
  57920. this._positionFunction = posFunction;
  57921. this._vertexFunction = vtxFunction;
  57922. }
  57923. return ModelShape;
  57924. }());
  57925. BABYLON.ModelShape = ModelShape;
  57926. /**
  57927. * Represents a Depth Sorted Particle in the solid particle system.
  57928. */
  57929. var DepthSortedParticle = /** @class */ (function () {
  57930. function DepthSortedParticle() {
  57931. /**
  57932. * Index of the particle in the "indices" array
  57933. */
  57934. this.ind = 0;
  57935. /**
  57936. * Length of the particle shape in the "indices" array
  57937. */
  57938. this.indicesLength = 0;
  57939. /**
  57940. * Squared distance from the particle to the camera
  57941. */
  57942. this.sqDistance = 0.0;
  57943. }
  57944. return DepthSortedParticle;
  57945. }());
  57946. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57947. })(BABYLON || (BABYLON = {}));
  57948. //# sourceMappingURL=babylon.solidParticle.js.map
  57949. var BABYLON;
  57950. (function (BABYLON) {
  57951. /**
  57952. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57953. *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.
  57954. * The SPS is also a particle system. It provides some methods to manage the particles.
  57955. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57956. *
  57957. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57958. */
  57959. var SolidParticleSystem = /** @class */ (function () {
  57960. /**
  57961. * Creates a SPS (Solid Particle System) object.
  57962. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57963. * @param scene (Scene) is the scene in which the SPS is added.
  57964. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57965. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57966. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57967. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57968. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57969. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57970. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57971. */
  57972. function SolidParticleSystem(name, scene, options) {
  57973. /**
  57974. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57975. * Example : var p = SPS.particles[i];
  57976. */
  57977. this.particles = new Array();
  57978. /**
  57979. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57980. */
  57981. this.nbParticles = 0;
  57982. /**
  57983. * If the particles must ever face the camera (default false). Useful for planar particles.
  57984. */
  57985. this.billboard = false;
  57986. /**
  57987. * Recompute normals when adding a shape
  57988. */
  57989. this.recomputeNormals = true;
  57990. /**
  57991. * This a counter ofr your own usage. It's not set by any SPS functions.
  57992. */
  57993. this.counter = 0;
  57994. /**
  57995. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57996. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57997. */
  57998. this.vars = {};
  57999. /**
  58000. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58001. */
  58002. this._bSphereOnly = false;
  58003. /**
  58004. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58005. */
  58006. this._bSphereRadiusFactor = 1.0;
  58007. this._positions = new Array();
  58008. this._indices = new Array();
  58009. this._normals = new Array();
  58010. this._colors = new Array();
  58011. this._uvs = new Array();
  58012. this._index = 0; // indices index
  58013. this._updatable = true;
  58014. this._pickable = false;
  58015. this._isVisibilityBoxLocked = false;
  58016. this._alwaysVisible = false;
  58017. this._depthSort = false;
  58018. this._shapeCounter = 0;
  58019. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58020. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58021. this._computeParticleColor = true;
  58022. this._computeParticleTexture = true;
  58023. this._computeParticleRotation = true;
  58024. this._computeParticleVertex = false;
  58025. this._computeBoundingBox = false;
  58026. this._depthSortParticles = true;
  58027. this._cam_axisZ = BABYLON.Vector3.Zero();
  58028. this._cam_axisY = BABYLON.Vector3.Zero();
  58029. this._cam_axisX = BABYLON.Vector3.Zero();
  58030. this._axisZ = BABYLON.Axis.Z;
  58031. this._camDir = BABYLON.Vector3.Zero();
  58032. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58033. this._rotMatrix = new BABYLON.Matrix();
  58034. this._invertMatrix = new BABYLON.Matrix();
  58035. this._rotated = BABYLON.Vector3.Zero();
  58036. this._quaternion = new BABYLON.Quaternion();
  58037. this._vertex = BABYLON.Vector3.Zero();
  58038. this._normal = BABYLON.Vector3.Zero();
  58039. this._yaw = 0.0;
  58040. this._pitch = 0.0;
  58041. this._roll = 0.0;
  58042. this._halfroll = 0.0;
  58043. this._halfpitch = 0.0;
  58044. this._halfyaw = 0.0;
  58045. this._sinRoll = 0.0;
  58046. this._cosRoll = 0.0;
  58047. this._sinPitch = 0.0;
  58048. this._cosPitch = 0.0;
  58049. this._sinYaw = 0.0;
  58050. this._cosYaw = 0.0;
  58051. this._mustUnrotateFixedNormals = false;
  58052. this._minimum = BABYLON.Vector3.Zero();
  58053. this._maximum = BABYLON.Vector3.Zero();
  58054. this._minBbox = BABYLON.Vector3.Zero();
  58055. this._maxBbox = BABYLON.Vector3.Zero();
  58056. this._particlesIntersect = false;
  58057. this._depthSortFunction = function (p1, p2) {
  58058. return (p2.sqDistance - p1.sqDistance);
  58059. };
  58060. this._needs32Bits = false;
  58061. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58062. this._scaledPivot = BABYLON.Vector3.Zero();
  58063. this._particleHasParent = false;
  58064. this.name = name;
  58065. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58066. this._camera = scene.activeCamera;
  58067. this._pickable = options ? options.isPickable : false;
  58068. this._depthSort = options ? options.enableDepthSort : false;
  58069. this._particlesIntersect = options ? options.particleIntersection : false;
  58070. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58071. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58072. if (options && options.updatable) {
  58073. this._updatable = options.updatable;
  58074. }
  58075. else {
  58076. this._updatable = true;
  58077. }
  58078. if (this._pickable) {
  58079. this.pickedParticles = [];
  58080. }
  58081. if (this._depthSort) {
  58082. this.depthSortedParticles = [];
  58083. }
  58084. }
  58085. /**
  58086. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58087. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58088. * @returns the created mesh
  58089. */
  58090. SolidParticleSystem.prototype.buildMesh = function () {
  58091. if (this.nbParticles === 0) {
  58092. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58093. this.addShape(triangle, 1);
  58094. triangle.dispose();
  58095. }
  58096. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58097. this._positions32 = new Float32Array(this._positions);
  58098. this._uvs32 = new Float32Array(this._uvs);
  58099. this._colors32 = new Float32Array(this._colors);
  58100. if (this.recomputeNormals) {
  58101. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58102. }
  58103. this._normals32 = new Float32Array(this._normals);
  58104. this._fixedNormal32 = new Float32Array(this._normals);
  58105. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58106. this._unrotateFixedNormals();
  58107. }
  58108. var vertexData = new BABYLON.VertexData();
  58109. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58110. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58111. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58112. if (this._uvs32) {
  58113. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58114. ;
  58115. }
  58116. if (this._colors32) {
  58117. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58118. }
  58119. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58120. vertexData.applyToMesh(mesh, this._updatable);
  58121. this.mesh = mesh;
  58122. this.mesh.isPickable = this._pickable;
  58123. // free memory
  58124. if (!this._depthSort) {
  58125. this._indices = null;
  58126. }
  58127. this._positions = null;
  58128. this._normals = null;
  58129. this._uvs = null;
  58130. this._colors = null;
  58131. if (!this._updatable) {
  58132. this.particles.length = 0;
  58133. }
  58134. return mesh;
  58135. };
  58136. /**
  58137. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58138. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58139. * Thus the particles generated from `digest()` have their property `position` set yet.
  58140. * @param mesh ( Mesh ) is the mesh to be digested
  58141. * @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
  58142. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58143. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58144. * @returns the current SPS
  58145. */
  58146. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58147. var size = (options && options.facetNb) || 1;
  58148. var number = (options && options.number) || 0;
  58149. var delta = (options && options.delta) || 0;
  58150. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58151. var meshInd = mesh.getIndices();
  58152. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58153. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58154. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58155. var f = 0; // facet counter
  58156. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58157. // compute size from number
  58158. if (number) {
  58159. number = (number > totalFacets) ? totalFacets : number;
  58160. size = Math.round(totalFacets / number);
  58161. delta = 0;
  58162. }
  58163. else {
  58164. size = (size > totalFacets) ? totalFacets : size;
  58165. }
  58166. var facetPos = []; // submesh positions
  58167. var facetInd = []; // submesh indices
  58168. var facetUV = []; // submesh UV
  58169. var facetCol = []; // submesh colors
  58170. var barycenter = BABYLON.Vector3.Zero();
  58171. var sizeO = size;
  58172. while (f < totalFacets) {
  58173. size = sizeO + Math.floor((1 + delta) * Math.random());
  58174. if (f > totalFacets - size) {
  58175. size = totalFacets - f;
  58176. }
  58177. // reset temp arrays
  58178. facetPos.length = 0;
  58179. facetInd.length = 0;
  58180. facetUV.length = 0;
  58181. facetCol.length = 0;
  58182. // iterate over "size" facets
  58183. var fi = 0;
  58184. for (var j = f * 3; j < (f + size) * 3; j++) {
  58185. facetInd.push(fi);
  58186. var i = meshInd[j];
  58187. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58188. if (meshUV) {
  58189. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58190. }
  58191. if (meshCol) {
  58192. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58193. }
  58194. fi++;
  58195. }
  58196. // create a model shape for each single particle
  58197. var idx = this.nbParticles;
  58198. var shape = this._posToShape(facetPos);
  58199. var shapeUV = this._uvsToShapeUV(facetUV);
  58200. // compute the barycenter of the shape
  58201. var v;
  58202. for (v = 0; v < shape.length; v++) {
  58203. barycenter.addInPlace(shape[v]);
  58204. }
  58205. barycenter.scaleInPlace(1 / shape.length);
  58206. // shift the shape from its barycenter to the origin
  58207. for (v = 0; v < shape.length; v++) {
  58208. shape[v].subtractInPlace(barycenter);
  58209. }
  58210. var bInfo;
  58211. if (this._particlesIntersect) {
  58212. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58213. }
  58214. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58215. // add the particle in the SPS
  58216. var currentPos = this._positions.length;
  58217. var currentInd = this._indices.length;
  58218. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58219. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58220. // initialize the particle position
  58221. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58222. this._index += shape.length;
  58223. idx++;
  58224. this.nbParticles++;
  58225. this._shapeCounter++;
  58226. f += size;
  58227. }
  58228. return this;
  58229. };
  58230. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58231. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58232. var index = 0;
  58233. var idx = 0;
  58234. for (var p = 0; p < this.particles.length; p++) {
  58235. this._particle = this.particles[p];
  58236. this._shape = this._particle._model._shape;
  58237. if (this._particle.rotationQuaternion) {
  58238. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58239. }
  58240. else {
  58241. this._yaw = this._particle.rotation.y;
  58242. this._pitch = this._particle.rotation.x;
  58243. this._roll = this._particle.rotation.z;
  58244. this._quaternionRotationYPR();
  58245. }
  58246. this._quaternionToRotationMatrix();
  58247. this._rotMatrix.invertToRef(this._invertMatrix);
  58248. for (var pt = 0; pt < this._shape.length; pt++) {
  58249. idx = index + pt * 3;
  58250. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58251. this._fixedNormal32[idx] = this._normal.x;
  58252. this._fixedNormal32[idx + 1] = this._normal.y;
  58253. this._fixedNormal32[idx + 2] = this._normal.z;
  58254. }
  58255. index = idx + 3;
  58256. }
  58257. };
  58258. //reset copy
  58259. SolidParticleSystem.prototype._resetCopy = function () {
  58260. this._copy.position.x = 0;
  58261. this._copy.position.y = 0;
  58262. this._copy.position.z = 0;
  58263. this._copy.rotation.x = 0;
  58264. this._copy.rotation.y = 0;
  58265. this._copy.rotation.z = 0;
  58266. this._copy.rotationQuaternion = null;
  58267. this._copy.scaling.x = 1.0;
  58268. this._copy.scaling.y = 1.0;
  58269. this._copy.scaling.z = 1.0;
  58270. this._copy.uvs.x = 0;
  58271. this._copy.uvs.y = 0;
  58272. this._copy.uvs.z = 1.0;
  58273. this._copy.uvs.w = 1.0;
  58274. this._copy.color = null;
  58275. this._copy.translateFromPivot = false;
  58276. };
  58277. // _meshBuilder : inserts the shape model in the global SPS mesh
  58278. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58279. var i;
  58280. var u = 0;
  58281. var c = 0;
  58282. var n = 0;
  58283. this._resetCopy();
  58284. if (options && options.positionFunction) { // call to custom positionFunction
  58285. options.positionFunction(this._copy, idx, idxInShape);
  58286. this._mustUnrotateFixedNormals = true;
  58287. }
  58288. if (this._copy.rotationQuaternion) {
  58289. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58290. }
  58291. else {
  58292. this._yaw = this._copy.rotation.y;
  58293. this._pitch = this._copy.rotation.x;
  58294. this._roll = this._copy.rotation.z;
  58295. this._quaternionRotationYPR();
  58296. }
  58297. this._quaternionToRotationMatrix();
  58298. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58299. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58300. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58301. if (this._copy.translateFromPivot) {
  58302. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58303. }
  58304. else {
  58305. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58306. }
  58307. for (i = 0; i < shape.length; i++) {
  58308. this._vertex.x = shape[i].x;
  58309. this._vertex.y = shape[i].y;
  58310. this._vertex.z = shape[i].z;
  58311. if (options && options.vertexFunction) {
  58312. options.vertexFunction(this._copy, this._vertex, i);
  58313. }
  58314. this._vertex.x *= this._copy.scaling.x;
  58315. this._vertex.y *= this._copy.scaling.y;
  58316. this._vertex.z *= this._copy.scaling.z;
  58317. this._vertex.x -= this._scaledPivot.x;
  58318. this._vertex.y -= this._scaledPivot.y;
  58319. this._vertex.z -= this._scaledPivot.z;
  58320. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58321. this._rotated.addInPlace(this._pivotBackTranslation);
  58322. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58323. if (meshUV) {
  58324. 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);
  58325. u += 2;
  58326. }
  58327. if (this._copy.color) {
  58328. this._color = this._copy.color;
  58329. }
  58330. else if (meshCol && meshCol[c] !== undefined) {
  58331. this._color.r = meshCol[c];
  58332. this._color.g = meshCol[c + 1];
  58333. this._color.b = meshCol[c + 2];
  58334. this._color.a = meshCol[c + 3];
  58335. }
  58336. else {
  58337. this._color.r = 1.0;
  58338. this._color.g = 1.0;
  58339. this._color.b = 1.0;
  58340. this._color.a = 1.0;
  58341. }
  58342. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58343. c += 4;
  58344. if (!this.recomputeNormals && meshNor) {
  58345. this._normal.x = meshNor[n];
  58346. this._normal.y = meshNor[n + 1];
  58347. this._normal.z = meshNor[n + 2];
  58348. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58349. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58350. n += 3;
  58351. }
  58352. }
  58353. for (i = 0; i < meshInd.length; i++) {
  58354. var current_ind = p + meshInd[i];
  58355. indices.push(current_ind);
  58356. if (current_ind > 65535) {
  58357. this._needs32Bits = true;
  58358. }
  58359. }
  58360. if (this._pickable) {
  58361. var nbfaces = meshInd.length / 3;
  58362. for (i = 0; i < nbfaces; i++) {
  58363. this.pickedParticles.push({ idx: idx, faceId: i });
  58364. }
  58365. }
  58366. if (this._depthSort) {
  58367. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58368. }
  58369. return this._copy;
  58370. };
  58371. // returns a shape array from positions array
  58372. SolidParticleSystem.prototype._posToShape = function (positions) {
  58373. var shape = [];
  58374. for (var i = 0; i < positions.length; i += 3) {
  58375. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58376. }
  58377. return shape;
  58378. };
  58379. // returns a shapeUV array from a Vector4 uvs
  58380. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58381. var shapeUV = [];
  58382. if (uvs) {
  58383. for (var i = 0; i < uvs.length; i++)
  58384. shapeUV.push(uvs[i]);
  58385. }
  58386. return shapeUV;
  58387. };
  58388. // adds a new particle object in the particles array
  58389. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58390. if (bInfo === void 0) { bInfo = null; }
  58391. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58392. this.particles.push(sp);
  58393. return sp;
  58394. };
  58395. /**
  58396. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58397. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58398. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58399. * @param nb (positive integer) the number of particles to be created from this model
  58400. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58401. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58402. * @returns the number of shapes in the system
  58403. */
  58404. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58405. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58406. var meshInd = mesh.getIndices();
  58407. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58408. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58409. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58410. var bbInfo;
  58411. if (this._particlesIntersect) {
  58412. bbInfo = mesh.getBoundingInfo();
  58413. }
  58414. var shape = this._posToShape(meshPos);
  58415. var shapeUV = this._uvsToShapeUV(meshUV);
  58416. var posfunc = options ? options.positionFunction : null;
  58417. var vtxfunc = options ? options.vertexFunction : null;
  58418. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58419. // particles
  58420. var sp;
  58421. var currentCopy;
  58422. var idx = this.nbParticles;
  58423. for (var i = 0; i < nb; i++) {
  58424. var currentPos = this._positions.length;
  58425. var currentInd = this._indices.length;
  58426. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58427. if (this._updatable) {
  58428. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58429. sp.position.copyFrom(currentCopy.position);
  58430. sp.rotation.copyFrom(currentCopy.rotation);
  58431. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58432. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58433. }
  58434. if (currentCopy.color && sp.color) {
  58435. sp.color.copyFrom(currentCopy.color);
  58436. }
  58437. sp.scaling.copyFrom(currentCopy.scaling);
  58438. sp.uvs.copyFrom(currentCopy.uvs);
  58439. }
  58440. this._index += shape.length;
  58441. idx++;
  58442. }
  58443. this.nbParticles += nb;
  58444. this._shapeCounter++;
  58445. return this._shapeCounter - 1;
  58446. };
  58447. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58448. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58449. this._resetCopy();
  58450. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58451. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58452. }
  58453. if (this._copy.rotationQuaternion) {
  58454. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58455. }
  58456. else {
  58457. this._yaw = this._copy.rotation.y;
  58458. this._pitch = this._copy.rotation.x;
  58459. this._roll = this._copy.rotation.z;
  58460. this._quaternionRotationYPR();
  58461. }
  58462. this._quaternionToRotationMatrix();
  58463. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58464. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58465. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58466. if (this._copy.translateFromPivot) {
  58467. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58468. }
  58469. else {
  58470. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58471. }
  58472. this._shape = particle._model._shape;
  58473. for (var pt = 0; pt < this._shape.length; pt++) {
  58474. this._vertex.x = this._shape[pt].x;
  58475. this._vertex.y = this._shape[pt].y;
  58476. this._vertex.z = this._shape[pt].z;
  58477. if (particle._model._vertexFunction) {
  58478. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58479. }
  58480. this._vertex.x *= this._copy.scaling.x;
  58481. this._vertex.y *= this._copy.scaling.y;
  58482. this._vertex.z *= this._copy.scaling.z;
  58483. this._vertex.x -= this._scaledPivot.x;
  58484. this._vertex.y -= this._scaledPivot.y;
  58485. this._vertex.z -= this._scaledPivot.z;
  58486. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58487. this._rotated.addInPlace(this._pivotBackTranslation);
  58488. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58489. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58490. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58491. }
  58492. particle.position.x = 0.0;
  58493. particle.position.y = 0.0;
  58494. particle.position.z = 0.0;
  58495. particle.rotation.x = 0.0;
  58496. particle.rotation.y = 0.0;
  58497. particle.rotation.z = 0.0;
  58498. particle.rotationQuaternion = null;
  58499. particle.scaling.x = 1.0;
  58500. particle.scaling.y = 1.0;
  58501. particle.scaling.z = 1.0;
  58502. particle.uvs.x = 0.0;
  58503. particle.uvs.y = 0.0;
  58504. particle.uvs.z = 1.0;
  58505. particle.uvs.w = 1.0;
  58506. particle.pivot.x = 0.0;
  58507. particle.pivot.y = 0.0;
  58508. particle.pivot.z = 0.0;
  58509. particle.translateFromPivot = false;
  58510. particle.parentId = null;
  58511. };
  58512. /**
  58513. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58514. * @returns the SPS.
  58515. */
  58516. SolidParticleSystem.prototype.rebuildMesh = function () {
  58517. for (var p = 0; p < this.particles.length; p++) {
  58518. this._rebuildParticle(this.particles[p]);
  58519. }
  58520. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58521. return this;
  58522. };
  58523. /**
  58524. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58525. * This method calls `updateParticle()` for each particle of the SPS.
  58526. * For an animated SPS, it is usually called within the render loop.
  58527. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58528. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58529. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58530. * @returns the SPS.
  58531. */
  58532. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58533. if (start === void 0) { start = 0; }
  58534. if (end === void 0) { end = this.nbParticles - 1; }
  58535. if (update === void 0) { update = true; }
  58536. if (!this._updatable) {
  58537. return this;
  58538. }
  58539. // custom beforeUpdate
  58540. this.beforeUpdateParticles(start, end, update);
  58541. this._cam_axisX.x = 1.0;
  58542. this._cam_axisX.y = 0.0;
  58543. this._cam_axisX.z = 0.0;
  58544. this._cam_axisY.x = 0.0;
  58545. this._cam_axisY.y = 1.0;
  58546. this._cam_axisY.z = 0.0;
  58547. this._cam_axisZ.x = 0.0;
  58548. this._cam_axisZ.y = 0.0;
  58549. this._cam_axisZ.z = 1.0;
  58550. // cases when the World Matrix is to be computed first
  58551. if (this.billboard || this._depthSort) {
  58552. this.mesh.computeWorldMatrix(true);
  58553. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58554. }
  58555. // if the particles will always face the camera
  58556. if (this.billboard) {
  58557. // compute the camera position and un-rotate it by the current mesh rotation
  58558. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58559. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58560. this._cam_axisZ.normalize();
  58561. // same for camera up vector extracted from the cam view matrix
  58562. var view = this._camera.getViewMatrix(true);
  58563. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58564. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58565. this._cam_axisY.normalize();
  58566. this._cam_axisX.normalize();
  58567. }
  58568. // if depthSort, compute the camera global position in the mesh local system
  58569. if (this._depthSort) {
  58570. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58571. }
  58572. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58573. var idx = 0; // current position index in the global array positions32
  58574. var index = 0; // position start index in the global array positions32 of the current particle
  58575. var colidx = 0; // current color index in the global array colors32
  58576. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58577. var uvidx = 0; // current uv index in the global array uvs32
  58578. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58579. var pt = 0; // current index in the particle model shape
  58580. if (this.mesh.isFacetDataEnabled) {
  58581. this._computeBoundingBox = true;
  58582. }
  58583. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58584. if (this._computeBoundingBox) {
  58585. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58586. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58587. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58588. }
  58589. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58590. if (this.mesh._boundingInfo) {
  58591. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58592. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58593. }
  58594. }
  58595. }
  58596. // particle loop
  58597. index = this.particles[start]._pos;
  58598. var vpos = (index / 3) | 0;
  58599. colorIndex = vpos * 4;
  58600. uvIndex = vpos * 2;
  58601. for (var p = start; p <= end; p++) {
  58602. this._particle = this.particles[p];
  58603. this._shape = this._particle._model._shape;
  58604. this._shapeUV = this._particle._model._shapeUV;
  58605. // call to custom user function to update the particle properties
  58606. this.updateParticle(this._particle);
  58607. // camera-particle distance for depth sorting
  58608. if (this._depthSort && this._depthSortParticles) {
  58609. var dsp = this.depthSortedParticles[p];
  58610. dsp.ind = this._particle._ind;
  58611. dsp.indicesLength = this._particle._model._indicesLength;
  58612. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58613. }
  58614. // skip the computations for inactive or already invisible particles
  58615. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58616. // increment indexes for the next particle
  58617. pt = this._shape.length;
  58618. index += pt * 3;
  58619. colorIndex += pt * 4;
  58620. uvIndex += pt * 2;
  58621. continue;
  58622. }
  58623. if (this._particle.isVisible) {
  58624. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58625. this._particleHasParent = (this._particle.parentId !== null);
  58626. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58627. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58628. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58629. // particle rotation matrix
  58630. if (this.billboard) {
  58631. this._particle.rotation.x = 0.0;
  58632. this._particle.rotation.y = 0.0;
  58633. }
  58634. if (this._computeParticleRotation || this.billboard) {
  58635. if (this._particle.rotationQuaternion) {
  58636. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58637. }
  58638. else {
  58639. this._yaw = this._particle.rotation.y;
  58640. this._pitch = this._particle.rotation.x;
  58641. this._roll = this._particle.rotation.z;
  58642. this._quaternionRotationYPR();
  58643. }
  58644. this._quaternionToRotationMatrix();
  58645. }
  58646. if (this._particleHasParent) {
  58647. this._parent = this.particles[this._particle.parentId];
  58648. 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];
  58649. 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];
  58650. 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];
  58651. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58652. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58653. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58654. if (this._computeParticleRotation || this.billboard) {
  58655. 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];
  58656. 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];
  58657. 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];
  58658. 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];
  58659. 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];
  58660. 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];
  58661. 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];
  58662. 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];
  58663. 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];
  58664. }
  58665. }
  58666. else {
  58667. this._particle._globalPosition.x = this._particle.position.x;
  58668. this._particle._globalPosition.y = this._particle.position.y;
  58669. this._particle._globalPosition.z = this._particle.position.z;
  58670. if (this._computeParticleRotation || this.billboard) {
  58671. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58672. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58673. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58674. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58675. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58676. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58677. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58678. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58679. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58680. }
  58681. }
  58682. if (this._particle.translateFromPivot) {
  58683. this._pivotBackTranslation.x = 0.0;
  58684. this._pivotBackTranslation.y = 0.0;
  58685. this._pivotBackTranslation.z = 0.0;
  58686. }
  58687. else {
  58688. this._pivotBackTranslation.x = this._scaledPivot.x;
  58689. this._pivotBackTranslation.y = this._scaledPivot.y;
  58690. this._pivotBackTranslation.z = this._scaledPivot.z;
  58691. }
  58692. // particle vertex loop
  58693. for (pt = 0; pt < this._shape.length; pt++) {
  58694. idx = index + pt * 3;
  58695. colidx = colorIndex + pt * 4;
  58696. uvidx = uvIndex + pt * 2;
  58697. this._vertex.x = this._shape[pt].x;
  58698. this._vertex.y = this._shape[pt].y;
  58699. this._vertex.z = this._shape[pt].z;
  58700. if (this._computeParticleVertex) {
  58701. this.updateParticleVertex(this._particle, this._vertex, pt);
  58702. }
  58703. // positions
  58704. this._vertex.x *= this._particle.scaling.x;
  58705. this._vertex.y *= this._particle.scaling.y;
  58706. this._vertex.z *= this._particle.scaling.z;
  58707. this._vertex.x -= this._scaledPivot.x;
  58708. this._vertex.y -= this._scaledPivot.y;
  58709. this._vertex.z -= this._scaledPivot.z;
  58710. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58711. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58712. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58713. this._rotated.x += this._pivotBackTranslation.x;
  58714. this._rotated.y += this._pivotBackTranslation.y;
  58715. this._rotated.z += this._pivotBackTranslation.z;
  58716. 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;
  58717. 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;
  58718. 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;
  58719. if (this._computeBoundingBox) {
  58720. if (this._positions32[idx] < this._minimum.x) {
  58721. this._minimum.x = this._positions32[idx];
  58722. }
  58723. if (this._positions32[idx] > this._maximum.x) {
  58724. this._maximum.x = this._positions32[idx];
  58725. }
  58726. if (this._positions32[idx + 1] < this._minimum.y) {
  58727. this._minimum.y = this._positions32[idx + 1];
  58728. }
  58729. if (this._positions32[idx + 1] > this._maximum.y) {
  58730. this._maximum.y = this._positions32[idx + 1];
  58731. }
  58732. if (this._positions32[idx + 2] < this._minimum.z) {
  58733. this._minimum.z = this._positions32[idx + 2];
  58734. }
  58735. if (this._positions32[idx + 2] > this._maximum.z) {
  58736. this._maximum.z = this._positions32[idx + 2];
  58737. }
  58738. }
  58739. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58740. if (!this._computeParticleVertex) {
  58741. this._normal.x = this._fixedNormal32[idx];
  58742. this._normal.y = this._fixedNormal32[idx + 1];
  58743. this._normal.z = this._fixedNormal32[idx + 2];
  58744. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58745. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58746. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58747. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58748. 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;
  58749. 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;
  58750. }
  58751. if (this._computeParticleColor && this._particle.color) {
  58752. this._colors32[colidx] = this._particle.color.r;
  58753. this._colors32[colidx + 1] = this._particle.color.g;
  58754. this._colors32[colidx + 2] = this._particle.color.b;
  58755. this._colors32[colidx + 3] = this._particle.color.a;
  58756. }
  58757. if (this._computeParticleTexture) {
  58758. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58759. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58760. }
  58761. }
  58762. }
  58763. // particle just set invisible : scaled to zero and positioned at the origin
  58764. else {
  58765. this._particle._stillInvisible = true; // mark the particle as invisible
  58766. for (pt = 0; pt < this._shape.length; pt++) {
  58767. idx = index + pt * 3;
  58768. colidx = colorIndex + pt * 4;
  58769. uvidx = uvIndex + pt * 2;
  58770. this._positions32[idx] = 0.0;
  58771. this._positions32[idx + 1] = 0.0;
  58772. this._positions32[idx + 2] = 0.0;
  58773. this._normals32[idx] = 0.0;
  58774. this._normals32[idx + 1] = 0.0;
  58775. this._normals32[idx + 2] = 0.0;
  58776. if (this._computeParticleColor && this._particle.color) {
  58777. this._colors32[colidx] = this._particle.color.r;
  58778. this._colors32[colidx + 1] = this._particle.color.g;
  58779. this._colors32[colidx + 2] = this._particle.color.b;
  58780. this._colors32[colidx + 3] = this._particle.color.a;
  58781. }
  58782. if (this._computeParticleTexture) {
  58783. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58784. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58785. }
  58786. }
  58787. }
  58788. // if the particle intersections must be computed : update the bbInfo
  58789. if (this._particlesIntersect) {
  58790. var bInfo = this._particle._boundingInfo;
  58791. var bBox = bInfo.boundingBox;
  58792. var bSphere = bInfo.boundingSphere;
  58793. if (!this._bSphereOnly) {
  58794. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58795. for (var b = 0; b < bBox.vectors.length; b++) {
  58796. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58797. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58798. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58799. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58800. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58801. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58802. 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;
  58803. 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;
  58804. 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;
  58805. }
  58806. bBox._update(this.mesh._worldMatrix);
  58807. }
  58808. // place and scale the particle bouding sphere in the SPS local system, then update it
  58809. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58810. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58811. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58812. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58813. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58814. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58815. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58816. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58817. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58818. 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));
  58819. bSphere._update(this.mesh._worldMatrix);
  58820. }
  58821. // increment indexes for the next particle
  58822. index = idx + 3;
  58823. colorIndex = colidx + 4;
  58824. uvIndex = uvidx + 2;
  58825. }
  58826. // if the VBO must be updated
  58827. if (update) {
  58828. if (this._computeParticleColor) {
  58829. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58830. }
  58831. if (this._computeParticleTexture) {
  58832. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58833. }
  58834. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58835. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58836. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58837. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58838. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58839. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58840. for (var i = 0; i < this._normals32.length; i++) {
  58841. this._fixedNormal32[i] = this._normals32[i];
  58842. }
  58843. }
  58844. if (!this.mesh.areNormalsFrozen) {
  58845. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58846. }
  58847. }
  58848. if (this._depthSort && this._depthSortParticles) {
  58849. this.depthSortedParticles.sort(this._depthSortFunction);
  58850. var dspl = this.depthSortedParticles.length;
  58851. var sorted = 0;
  58852. var lind = 0;
  58853. var sind = 0;
  58854. var sid = 0;
  58855. for (sorted = 0; sorted < dspl; sorted++) {
  58856. lind = this.depthSortedParticles[sorted].indicesLength;
  58857. sind = this.depthSortedParticles[sorted].ind;
  58858. for (var i = 0; i < lind; i++) {
  58859. this._indices32[sid] = this._indices[sind + i];
  58860. sid++;
  58861. }
  58862. }
  58863. this.mesh.updateIndices(this._indices32);
  58864. }
  58865. }
  58866. if (this._computeBoundingBox) {
  58867. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58868. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58869. }
  58870. this.afterUpdateParticles(start, end, update);
  58871. return this;
  58872. };
  58873. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58874. this._halfroll = this._roll * 0.5;
  58875. this._halfpitch = this._pitch * 0.5;
  58876. this._halfyaw = this._yaw * 0.5;
  58877. this._sinRoll = Math.sin(this._halfroll);
  58878. this._cosRoll = Math.cos(this._halfroll);
  58879. this._sinPitch = Math.sin(this._halfpitch);
  58880. this._cosPitch = Math.cos(this._halfpitch);
  58881. this._sinYaw = Math.sin(this._halfyaw);
  58882. this._cosYaw = Math.cos(this._halfyaw);
  58883. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58884. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58885. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58886. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58887. };
  58888. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58889. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58890. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58891. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58892. this._rotMatrix.m[3] = 0;
  58893. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58894. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58895. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58896. this._rotMatrix.m[7] = 0;
  58897. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58898. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58899. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58900. this._rotMatrix.m[11] = 0;
  58901. this._rotMatrix.m[12] = 0;
  58902. this._rotMatrix.m[13] = 0;
  58903. this._rotMatrix.m[14] = 0;
  58904. this._rotMatrix.m[15] = 1.0;
  58905. };
  58906. /**
  58907. * Disposes the SPS.
  58908. */
  58909. SolidParticleSystem.prototype.dispose = function () {
  58910. this.mesh.dispose();
  58911. this.vars = null;
  58912. // drop references to internal big arrays for the GC
  58913. this._positions = null;
  58914. this._indices = null;
  58915. this._normals = null;
  58916. this._uvs = null;
  58917. this._colors = null;
  58918. this._indices32 = null;
  58919. this._positions32 = null;
  58920. this._normals32 = null;
  58921. this._fixedNormal32 = null;
  58922. this._uvs32 = null;
  58923. this._colors32 = null;
  58924. this.pickedParticles = null;
  58925. };
  58926. /**
  58927. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58928. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58929. * @returns the SPS.
  58930. */
  58931. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58932. if (!this._isVisibilityBoxLocked) {
  58933. this.mesh.refreshBoundingInfo();
  58934. }
  58935. return this;
  58936. };
  58937. /**
  58938. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58939. * @param size the size (float) of the visibility box
  58940. * note : this doesn't lock the SPS mesh bounding box.
  58941. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58942. */
  58943. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58944. var vis = size / 2;
  58945. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58946. };
  58947. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58948. /**
  58949. * Gets whether the SPS as always visible or not
  58950. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58951. */
  58952. get: function () {
  58953. return this._alwaysVisible;
  58954. },
  58955. /**
  58956. * Sets the SPS as always visible or not
  58957. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58958. */
  58959. set: function (val) {
  58960. this._alwaysVisible = val;
  58961. this.mesh.alwaysSelectAsActiveMesh = val;
  58962. },
  58963. enumerable: true,
  58964. configurable: true
  58965. });
  58966. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58967. /**
  58968. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58969. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58970. */
  58971. get: function () {
  58972. return this._isVisibilityBoxLocked;
  58973. },
  58974. /**
  58975. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58976. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58977. */
  58978. set: function (val) {
  58979. this._isVisibilityBoxLocked = val;
  58980. var boundingInfo = this.mesh.getBoundingInfo();
  58981. boundingInfo.isLocked = val;
  58982. },
  58983. enumerable: true,
  58984. configurable: true
  58985. });
  58986. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58987. /**
  58988. * Gets if `setParticles()` computes the particle rotations or not.
  58989. * Default value : true. The SPS is faster when it's set to false.
  58990. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58991. */
  58992. get: function () {
  58993. return this._computeParticleRotation;
  58994. },
  58995. /**
  58996. * Tells to `setParticles()` to compute the particle rotations or not.
  58997. * Default value : true. The SPS is faster when it's set to false.
  58998. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58999. */
  59000. set: function (val) {
  59001. this._computeParticleRotation = val;
  59002. },
  59003. enumerable: true,
  59004. configurable: true
  59005. });
  59006. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59007. /**
  59008. * Gets if `setParticles()` computes the particle colors or not.
  59009. * Default value : true. The SPS is faster when it's set to false.
  59010. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59011. */
  59012. get: function () {
  59013. return this._computeParticleColor;
  59014. },
  59015. /**
  59016. * Tells to `setParticles()` to compute the particle colors or not.
  59017. * Default value : true. The SPS is faster when it's set to false.
  59018. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59019. */
  59020. set: function (val) {
  59021. this._computeParticleColor = val;
  59022. },
  59023. enumerable: true,
  59024. configurable: true
  59025. });
  59026. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59027. /**
  59028. * Gets if `setParticles()` computes the particle textures or not.
  59029. * Default value : true. The SPS is faster when it's set to false.
  59030. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59031. */
  59032. get: function () {
  59033. return this._computeParticleTexture;
  59034. },
  59035. set: function (val) {
  59036. this._computeParticleTexture = val;
  59037. },
  59038. enumerable: true,
  59039. configurable: true
  59040. });
  59041. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59042. /**
  59043. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59044. * Default value : false. The SPS is faster when it's set to false.
  59045. * Note : the particle custom vertex positions aren't stored values.
  59046. */
  59047. get: function () {
  59048. return this._computeParticleVertex;
  59049. },
  59050. /**
  59051. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59052. * Default value : false. The SPS is faster when it's set to false.
  59053. * Note : the particle custom vertex positions aren't stored values.
  59054. */
  59055. set: function (val) {
  59056. this._computeParticleVertex = val;
  59057. },
  59058. enumerable: true,
  59059. configurable: true
  59060. });
  59061. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59062. /**
  59063. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59064. */
  59065. get: function () {
  59066. return this._computeBoundingBox;
  59067. },
  59068. /**
  59069. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59070. */
  59071. set: function (val) {
  59072. this._computeBoundingBox = val;
  59073. },
  59074. enumerable: true,
  59075. configurable: true
  59076. });
  59077. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59078. /**
  59079. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59080. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59081. * Default : `true`
  59082. */
  59083. get: function () {
  59084. return this._depthSortParticles;
  59085. },
  59086. /**
  59087. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59088. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59089. * Default : `true`
  59090. */
  59091. set: function (val) {
  59092. this._depthSortParticles = val;
  59093. },
  59094. enumerable: true,
  59095. configurable: true
  59096. });
  59097. // =======================================================================
  59098. // Particle behavior logic
  59099. // these following methods may be overwritten by the user to fit his needs
  59100. /**
  59101. * This function does nothing. It may be overwritten to set all the particle first values.
  59102. * The SPS doesn't call this function, you may have to call it by your own.
  59103. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59104. */
  59105. SolidParticleSystem.prototype.initParticles = function () {
  59106. };
  59107. /**
  59108. * This function does nothing. It may be overwritten to recycle a particle.
  59109. * The SPS doesn't call this function, you may have to call it by your own.
  59110. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59111. * @param particle The particle to recycle
  59112. * @returns the recycled particle
  59113. */
  59114. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59115. return particle;
  59116. };
  59117. /**
  59118. * Updates a particle : this function should be overwritten by the user.
  59119. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59120. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59121. * @example : just set a particle position or velocity and recycle conditions
  59122. * @param particle The particle to update
  59123. * @returns the updated particle
  59124. */
  59125. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59126. return particle;
  59127. };
  59128. /**
  59129. * Updates a vertex of a particle : it can be overwritten by the user.
  59130. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59131. * @param particle the current particle
  59132. * @param vertex the current index of the current particle
  59133. * @param pt the index of the current vertex in the particle shape
  59134. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59135. * @example : just set a vertex particle position
  59136. * @returns the updated vertex
  59137. */
  59138. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59139. return vertex;
  59140. };
  59141. /**
  59142. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59143. * This does nothing and may be overwritten by the user.
  59144. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59145. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59146. * @param update the boolean update value actually passed to setParticles()
  59147. */
  59148. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59149. };
  59150. /**
  59151. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59152. * This will be passed three parameters.
  59153. * This does nothing and may be overwritten by the user.
  59154. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59155. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59156. * @param update the boolean update value actually passed to setParticles()
  59157. */
  59158. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59159. };
  59160. return SolidParticleSystem;
  59161. }());
  59162. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59163. })(BABYLON || (BABYLON = {}));
  59164. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59165. var BABYLON;
  59166. (function (BABYLON) {
  59167. var ShaderMaterial = /** @class */ (function (_super) {
  59168. __extends(ShaderMaterial, _super);
  59169. function ShaderMaterial(name, scene, shaderPath, options) {
  59170. var _this = _super.call(this, name, scene) || this;
  59171. _this._textures = {};
  59172. _this._textureArrays = {};
  59173. _this._floats = {};
  59174. _this._ints = {};
  59175. _this._floatsArrays = {};
  59176. _this._colors3 = {};
  59177. _this._colors3Arrays = {};
  59178. _this._colors4 = {};
  59179. _this._vectors2 = {};
  59180. _this._vectors3 = {};
  59181. _this._vectors4 = {};
  59182. _this._matrices = {};
  59183. _this._matrices3x3 = {};
  59184. _this._matrices2x2 = {};
  59185. _this._vectors2Arrays = {};
  59186. _this._vectors3Arrays = {};
  59187. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59188. _this._shaderPath = shaderPath;
  59189. options.needAlphaBlending = options.needAlphaBlending || false;
  59190. options.needAlphaTesting = options.needAlphaTesting || false;
  59191. options.attributes = options.attributes || ["position", "normal", "uv"];
  59192. options.uniforms = options.uniforms || ["worldViewProjection"];
  59193. options.uniformBuffers = options.uniformBuffers || [];
  59194. options.samplers = options.samplers || [];
  59195. options.defines = options.defines || [];
  59196. _this._options = options;
  59197. return _this;
  59198. }
  59199. ShaderMaterial.prototype.getClassName = function () {
  59200. return "ShaderMaterial";
  59201. };
  59202. ShaderMaterial.prototype.needAlphaBlending = function () {
  59203. return this._options.needAlphaBlending;
  59204. };
  59205. ShaderMaterial.prototype.needAlphaTesting = function () {
  59206. return this._options.needAlphaTesting;
  59207. };
  59208. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59209. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59210. this._options.uniforms.push(uniformName);
  59211. }
  59212. };
  59213. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59214. if (this._options.samplers.indexOf(name) === -1) {
  59215. this._options.samplers.push(name);
  59216. }
  59217. this._textures[name] = texture;
  59218. return this;
  59219. };
  59220. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59221. if (this._options.samplers.indexOf(name) === -1) {
  59222. this._options.samplers.push(name);
  59223. }
  59224. this._checkUniform(name);
  59225. this._textureArrays[name] = textures;
  59226. return this;
  59227. };
  59228. ShaderMaterial.prototype.setFloat = function (name, value) {
  59229. this._checkUniform(name);
  59230. this._floats[name] = value;
  59231. return this;
  59232. };
  59233. ShaderMaterial.prototype.setInt = function (name, value) {
  59234. this._checkUniform(name);
  59235. this._ints[name] = value;
  59236. return this;
  59237. };
  59238. ShaderMaterial.prototype.setFloats = function (name, value) {
  59239. this._checkUniform(name);
  59240. this._floatsArrays[name] = value;
  59241. return this;
  59242. };
  59243. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59244. this._checkUniform(name);
  59245. this._colors3[name] = value;
  59246. return this;
  59247. };
  59248. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59249. this._checkUniform(name);
  59250. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59251. color.toArray(arr, arr.length);
  59252. return arr;
  59253. }, []);
  59254. return this;
  59255. };
  59256. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59257. this._checkUniform(name);
  59258. this._colors4[name] = value;
  59259. return this;
  59260. };
  59261. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59262. this._checkUniform(name);
  59263. this._vectors2[name] = value;
  59264. return this;
  59265. };
  59266. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59267. this._checkUniform(name);
  59268. this._vectors3[name] = value;
  59269. return this;
  59270. };
  59271. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59272. this._checkUniform(name);
  59273. this._vectors4[name] = value;
  59274. return this;
  59275. };
  59276. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59277. this._checkUniform(name);
  59278. this._matrices[name] = value;
  59279. return this;
  59280. };
  59281. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59282. this._checkUniform(name);
  59283. this._matrices3x3[name] = value;
  59284. return this;
  59285. };
  59286. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59287. this._checkUniform(name);
  59288. this._matrices2x2[name] = value;
  59289. return this;
  59290. };
  59291. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59292. this._checkUniform(name);
  59293. this._vectors2Arrays[name] = value;
  59294. return this;
  59295. };
  59296. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59297. this._checkUniform(name);
  59298. this._vectors3Arrays[name] = value;
  59299. return this;
  59300. };
  59301. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59302. if (!mesh) {
  59303. return true;
  59304. }
  59305. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59306. return false;
  59307. }
  59308. return false;
  59309. };
  59310. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59311. var scene = this.getScene();
  59312. var engine = scene.getEngine();
  59313. if (!this.checkReadyOnEveryCall) {
  59314. if (this._renderId === scene.getRenderId()) {
  59315. if (this._checkCache(scene, mesh, useInstances)) {
  59316. return true;
  59317. }
  59318. }
  59319. }
  59320. // Instances
  59321. var defines = [];
  59322. var attribs = [];
  59323. var fallbacks = new BABYLON.EffectFallbacks();
  59324. if (useInstances) {
  59325. defines.push("#define INSTANCES");
  59326. }
  59327. for (var index = 0; index < this._options.defines.length; index++) {
  59328. defines.push(this._options.defines[index]);
  59329. }
  59330. for (var index = 0; index < this._options.attributes.length; index++) {
  59331. attribs.push(this._options.attributes[index]);
  59332. }
  59333. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59334. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59335. defines.push("#define VERTEXCOLOR");
  59336. }
  59337. // Bones
  59338. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59339. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59340. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59341. if (mesh.numBoneInfluencers > 4) {
  59342. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59343. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59344. }
  59345. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59346. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59347. fallbacks.addCPUSkinningFallback(0, mesh);
  59348. if (this._options.uniforms.indexOf("mBones") === -1) {
  59349. this._options.uniforms.push("mBones");
  59350. }
  59351. }
  59352. else {
  59353. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59354. }
  59355. // Textures
  59356. for (var name in this._textures) {
  59357. if (!this._textures[name].isReady()) {
  59358. return false;
  59359. }
  59360. }
  59361. // Alpha test
  59362. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59363. defines.push("#define ALPHATEST");
  59364. }
  59365. var previousEffect = this._effect;
  59366. var join = defines.join("\n");
  59367. this._effect = engine.createEffect(this._shaderPath, {
  59368. attributes: attribs,
  59369. uniformsNames: this._options.uniforms,
  59370. uniformBuffersNames: this._options.uniformBuffers,
  59371. samplers: this._options.samplers,
  59372. defines: join,
  59373. fallbacks: fallbacks,
  59374. onCompiled: this.onCompiled,
  59375. onError: this.onError
  59376. }, engine);
  59377. if (!this._effect.isReady()) {
  59378. return false;
  59379. }
  59380. if (previousEffect !== this._effect) {
  59381. scene.resetCachedMaterial();
  59382. }
  59383. this._renderId = scene.getRenderId();
  59384. return true;
  59385. };
  59386. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59387. var scene = this.getScene();
  59388. if (!this._effect) {
  59389. return;
  59390. }
  59391. if (this._options.uniforms.indexOf("world") !== -1) {
  59392. this._effect.setMatrix("world", world);
  59393. }
  59394. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59395. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59396. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59397. }
  59398. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59399. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59400. }
  59401. };
  59402. ShaderMaterial.prototype.bind = function (world, mesh) {
  59403. // Std values
  59404. this.bindOnlyWorldMatrix(world);
  59405. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59406. if (this._options.uniforms.indexOf("view") !== -1) {
  59407. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59408. }
  59409. if (this._options.uniforms.indexOf("projection") !== -1) {
  59410. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59411. }
  59412. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59413. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59414. }
  59415. // Bones
  59416. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59417. var name;
  59418. // Texture
  59419. for (name in this._textures) {
  59420. this._effect.setTexture(name, this._textures[name]);
  59421. }
  59422. // Texture arrays
  59423. for (name in this._textureArrays) {
  59424. this._effect.setTextureArray(name, this._textureArrays[name]);
  59425. }
  59426. // Int
  59427. for (name in this._ints) {
  59428. this._effect.setInt(name, this._ints[name]);
  59429. }
  59430. // Float
  59431. for (name in this._floats) {
  59432. this._effect.setFloat(name, this._floats[name]);
  59433. }
  59434. // Floats
  59435. for (name in this._floatsArrays) {
  59436. this._effect.setArray(name, this._floatsArrays[name]);
  59437. }
  59438. // Color3
  59439. for (name in this._colors3) {
  59440. this._effect.setColor3(name, this._colors3[name]);
  59441. }
  59442. for (name in this._colors3Arrays) {
  59443. this._effect.setArray3(name, this._colors3Arrays[name]);
  59444. }
  59445. // Color4
  59446. for (name in this._colors4) {
  59447. var color = this._colors4[name];
  59448. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59449. }
  59450. // Vector2
  59451. for (name in this._vectors2) {
  59452. this._effect.setVector2(name, this._vectors2[name]);
  59453. }
  59454. // Vector3
  59455. for (name in this._vectors3) {
  59456. this._effect.setVector3(name, this._vectors3[name]);
  59457. }
  59458. // Vector4
  59459. for (name in this._vectors4) {
  59460. this._effect.setVector4(name, this._vectors4[name]);
  59461. }
  59462. // Matrix
  59463. for (name in this._matrices) {
  59464. this._effect.setMatrix(name, this._matrices[name]);
  59465. }
  59466. // Matrix 3x3
  59467. for (name in this._matrices3x3) {
  59468. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59469. }
  59470. // Matrix 2x2
  59471. for (name in this._matrices2x2) {
  59472. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59473. }
  59474. // Vector2Array
  59475. for (name in this._vectors2Arrays) {
  59476. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59477. }
  59478. // Vector3Array
  59479. for (name in this._vectors3Arrays) {
  59480. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59481. }
  59482. }
  59483. this._afterBind(mesh);
  59484. };
  59485. ShaderMaterial.prototype.getActiveTextures = function () {
  59486. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59487. for (var name in this._textures) {
  59488. activeTextures.push(this._textures[name]);
  59489. }
  59490. for (var name in this._textureArrays) {
  59491. var array = this._textureArrays[name];
  59492. for (var index = 0; index < array.length; index++) {
  59493. activeTextures.push(array[index]);
  59494. }
  59495. }
  59496. return activeTextures;
  59497. };
  59498. ShaderMaterial.prototype.hasTexture = function (texture) {
  59499. if (_super.prototype.hasTexture.call(this, texture)) {
  59500. return true;
  59501. }
  59502. for (var name in this._textures) {
  59503. if (this._textures[name] === texture) {
  59504. return true;
  59505. }
  59506. }
  59507. for (var name in this._textureArrays) {
  59508. var array = this._textureArrays[name];
  59509. for (var index = 0; index < array.length; index++) {
  59510. if (array[index] === texture) {
  59511. return true;
  59512. }
  59513. }
  59514. }
  59515. return false;
  59516. };
  59517. ShaderMaterial.prototype.clone = function (name) {
  59518. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59519. return newShaderMaterial;
  59520. };
  59521. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59522. if (forceDisposeTextures) {
  59523. var name;
  59524. for (name in this._textures) {
  59525. this._textures[name].dispose();
  59526. }
  59527. for (name in this._textureArrays) {
  59528. var array = this._textureArrays[name];
  59529. for (var index = 0; index < array.length; index++) {
  59530. array[index].dispose();
  59531. }
  59532. }
  59533. }
  59534. this._textures = {};
  59535. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59536. };
  59537. ShaderMaterial.prototype.serialize = function () {
  59538. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59539. serializationObject.customType = "BABYLON.ShaderMaterial";
  59540. serializationObject.options = this._options;
  59541. serializationObject.shaderPath = this._shaderPath;
  59542. var name;
  59543. // Texture
  59544. serializationObject.textures = {};
  59545. for (name in this._textures) {
  59546. serializationObject.textures[name] = this._textures[name].serialize();
  59547. }
  59548. // Texture arrays
  59549. serializationObject.textureArrays = {};
  59550. for (name in this._textureArrays) {
  59551. serializationObject.textureArrays[name] = [];
  59552. var array = this._textureArrays[name];
  59553. for (var index = 0; index < array.length; index++) {
  59554. serializationObject.textureArrays[name].push(array[index].serialize());
  59555. }
  59556. }
  59557. // Float
  59558. serializationObject.floats = {};
  59559. for (name in this._floats) {
  59560. serializationObject.floats[name] = this._floats[name];
  59561. }
  59562. // Float s
  59563. serializationObject.FloatArrays = {};
  59564. for (name in this._floatsArrays) {
  59565. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59566. }
  59567. // Color3
  59568. serializationObject.colors3 = {};
  59569. for (name in this._colors3) {
  59570. serializationObject.colors3[name] = this._colors3[name].asArray();
  59571. }
  59572. // Color3 array
  59573. serializationObject.colors3Arrays = {};
  59574. for (name in this._colors3Arrays) {
  59575. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59576. }
  59577. // Color4
  59578. serializationObject.colors4 = {};
  59579. for (name in this._colors4) {
  59580. serializationObject.colors4[name] = this._colors4[name].asArray();
  59581. }
  59582. // Vector2
  59583. serializationObject.vectors2 = {};
  59584. for (name in this._vectors2) {
  59585. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59586. }
  59587. // Vector3
  59588. serializationObject.vectors3 = {};
  59589. for (name in this._vectors3) {
  59590. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59591. }
  59592. // Vector4
  59593. serializationObject.vectors4 = {};
  59594. for (name in this._vectors4) {
  59595. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59596. }
  59597. // Matrix
  59598. serializationObject.matrices = {};
  59599. for (name in this._matrices) {
  59600. serializationObject.matrices[name] = this._matrices[name].asArray();
  59601. }
  59602. // Matrix 3x3
  59603. serializationObject.matrices3x3 = {};
  59604. for (name in this._matrices3x3) {
  59605. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59606. }
  59607. // Matrix 2x2
  59608. serializationObject.matrices2x2 = {};
  59609. for (name in this._matrices2x2) {
  59610. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59611. }
  59612. // Vector2Array
  59613. serializationObject.vectors2Arrays = {};
  59614. for (name in this._vectors2Arrays) {
  59615. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59616. }
  59617. // Vector3Array
  59618. serializationObject.vectors3Arrays = {};
  59619. for (name in this._vectors3Arrays) {
  59620. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59621. }
  59622. return serializationObject;
  59623. };
  59624. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59625. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59626. var name;
  59627. // Texture
  59628. for (name in source.textures) {
  59629. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59630. }
  59631. // Texture arrays
  59632. for (name in source.textureArrays) {
  59633. var array = source.textureArrays[name];
  59634. var textureArray = new Array();
  59635. for (var index = 0; index < array.length; index++) {
  59636. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59637. }
  59638. material.setTextureArray(name, textureArray);
  59639. }
  59640. // Float
  59641. for (name in source.floats) {
  59642. material.setFloat(name, source.floats[name]);
  59643. }
  59644. // Float s
  59645. for (name in source.floatsArrays) {
  59646. material.setFloats(name, source.floatsArrays[name]);
  59647. }
  59648. // Color3
  59649. for (name in source.colors3) {
  59650. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59651. }
  59652. // Color3 arrays
  59653. for (name in source.colors3Arrays) {
  59654. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59655. if (i % 3 === 0) {
  59656. arr.push([num]);
  59657. }
  59658. else {
  59659. arr[arr.length - 1].push(num);
  59660. }
  59661. return arr;
  59662. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59663. material.setColor3Array(name, colors);
  59664. }
  59665. // Color4
  59666. for (name in source.colors4) {
  59667. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59668. }
  59669. // Vector2
  59670. for (name in source.vectors2) {
  59671. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59672. }
  59673. // Vector3
  59674. for (name in source.vectors3) {
  59675. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59676. }
  59677. // Vector4
  59678. for (name in source.vectors4) {
  59679. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59680. }
  59681. // Matrix
  59682. for (name in source.matrices) {
  59683. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59684. }
  59685. // Matrix 3x3
  59686. for (name in source.matrices3x3) {
  59687. material.setMatrix3x3(name, source.matrices3x3[name]);
  59688. }
  59689. // Matrix 2x2
  59690. for (name in source.matrices2x2) {
  59691. material.setMatrix2x2(name, source.matrices2x2[name]);
  59692. }
  59693. // Vector2Array
  59694. for (name in source.vectors2Arrays) {
  59695. material.setArray2(name, source.vectors2Arrays[name]);
  59696. }
  59697. // Vector3Array
  59698. for (name in source.vectors3Arrays) {
  59699. material.setArray3(name, source.vectors3Arrays[name]);
  59700. }
  59701. return material;
  59702. };
  59703. return ShaderMaterial;
  59704. }(BABYLON.Material));
  59705. BABYLON.ShaderMaterial = ShaderMaterial;
  59706. })(BABYLON || (BABYLON = {}));
  59707. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59708. var BABYLON;
  59709. (function (BABYLON) {
  59710. var GroundMesh = /** @class */ (function (_super) {
  59711. __extends(GroundMesh, _super);
  59712. function GroundMesh(name, scene) {
  59713. var _this = _super.call(this, name, scene) || this;
  59714. _this.generateOctree = false;
  59715. return _this;
  59716. }
  59717. GroundMesh.prototype.getClassName = function () {
  59718. return "GroundMesh";
  59719. };
  59720. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59721. get: function () {
  59722. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59723. },
  59724. enumerable: true,
  59725. configurable: true
  59726. });
  59727. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59728. get: function () {
  59729. return this._subdivisionsX;
  59730. },
  59731. enumerable: true,
  59732. configurable: true
  59733. });
  59734. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59735. get: function () {
  59736. return this._subdivisionsY;
  59737. },
  59738. enumerable: true,
  59739. configurable: true
  59740. });
  59741. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59742. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59743. this._subdivisionsX = chunksCount;
  59744. this._subdivisionsY = chunksCount;
  59745. this.subdivide(chunksCount);
  59746. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59747. };
  59748. /**
  59749. * Returns a height (y) value in the Worl system :
  59750. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59751. * Returns the ground y position if (x, z) are outside the ground surface.
  59752. */
  59753. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59754. var world = this.getWorldMatrix();
  59755. var invMat = BABYLON.Tmp.Matrix[5];
  59756. world.invertToRef(invMat);
  59757. var tmpVect = BABYLON.Tmp.Vector3[8];
  59758. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59759. x = tmpVect.x;
  59760. z = tmpVect.z;
  59761. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59762. return this.position.y;
  59763. }
  59764. if (!this._heightQuads || this._heightQuads.length == 0) {
  59765. this._initHeightQuads();
  59766. this._computeHeightQuads();
  59767. }
  59768. var facet = this._getFacetAt(x, z);
  59769. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59770. // return y in the World system
  59771. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59772. return tmpVect.y;
  59773. };
  59774. /**
  59775. * Returns a normalized vector (Vector3) orthogonal to the ground
  59776. * at the ground coordinates (x, z) expressed in the World system.
  59777. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59778. */
  59779. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59780. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59781. this.getNormalAtCoordinatesToRef(x, z, normal);
  59782. return normal;
  59783. };
  59784. /**
  59785. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59786. * at the ground coordinates (x, z) expressed in the World system.
  59787. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59788. * Returns the GroundMesh.
  59789. */
  59790. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59791. var world = this.getWorldMatrix();
  59792. var tmpMat = BABYLON.Tmp.Matrix[5];
  59793. world.invertToRef(tmpMat);
  59794. var tmpVect = BABYLON.Tmp.Vector3[8];
  59795. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59796. x = tmpVect.x;
  59797. z = tmpVect.z;
  59798. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59799. return this;
  59800. }
  59801. if (!this._heightQuads || this._heightQuads.length == 0) {
  59802. this._initHeightQuads();
  59803. this._computeHeightQuads();
  59804. }
  59805. var facet = this._getFacetAt(x, z);
  59806. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59807. return this;
  59808. };
  59809. /**
  59810. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59811. * if the ground has been updated.
  59812. * This can be used in the render loop.
  59813. * Returns the GroundMesh.
  59814. */
  59815. GroundMesh.prototype.updateCoordinateHeights = function () {
  59816. if (!this._heightQuads || this._heightQuads.length == 0) {
  59817. this._initHeightQuads();
  59818. }
  59819. this._computeHeightQuads();
  59820. return this;
  59821. };
  59822. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59823. GroundMesh.prototype._getFacetAt = function (x, z) {
  59824. // retrieve col and row from x, z coordinates in the ground local system
  59825. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59826. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59827. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59828. var facet;
  59829. if (z < quad.slope.x * x + quad.slope.y) {
  59830. facet = quad.facet1;
  59831. }
  59832. else {
  59833. facet = quad.facet2;
  59834. }
  59835. return facet;
  59836. };
  59837. // Creates and populates the heightMap array with "facet" elements :
  59838. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59839. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59840. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59841. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59842. // Returns the GroundMesh.
  59843. GroundMesh.prototype._initHeightQuads = function () {
  59844. var subdivisionsX = this._subdivisionsX;
  59845. var subdivisionsY = this._subdivisionsY;
  59846. this._heightQuads = new Array();
  59847. for (var row = 0; row < subdivisionsY; row++) {
  59848. for (var col = 0; col < subdivisionsX; col++) {
  59849. 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) };
  59850. this._heightQuads[row * subdivisionsX + col] = quad;
  59851. }
  59852. }
  59853. return this;
  59854. };
  59855. // Compute each quad element values and update the the heightMap array :
  59856. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59857. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59858. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59859. // Returns the GroundMesh.
  59860. GroundMesh.prototype._computeHeightQuads = function () {
  59861. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59862. if (!positions) {
  59863. return this;
  59864. }
  59865. var v1 = BABYLON.Tmp.Vector3[3];
  59866. var v2 = BABYLON.Tmp.Vector3[2];
  59867. var v3 = BABYLON.Tmp.Vector3[1];
  59868. var v4 = BABYLON.Tmp.Vector3[0];
  59869. var v1v2 = BABYLON.Tmp.Vector3[4];
  59870. var v1v3 = BABYLON.Tmp.Vector3[5];
  59871. var v1v4 = BABYLON.Tmp.Vector3[6];
  59872. var norm1 = BABYLON.Tmp.Vector3[7];
  59873. var norm2 = BABYLON.Tmp.Vector3[8];
  59874. var i = 0;
  59875. var j = 0;
  59876. var k = 0;
  59877. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59878. var h = 0;
  59879. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59880. var d2 = 0;
  59881. var subdivisionsX = this._subdivisionsX;
  59882. var subdivisionsY = this._subdivisionsY;
  59883. for (var row = 0; row < subdivisionsY; row++) {
  59884. for (var col = 0; col < subdivisionsX; col++) {
  59885. i = col * 3;
  59886. j = row * (subdivisionsX + 1) * 3;
  59887. k = (row + 1) * (subdivisionsX + 1) * 3;
  59888. v1.x = positions[j + i];
  59889. v1.y = positions[j + i + 1];
  59890. v1.z = positions[j + i + 2];
  59891. v2.x = positions[j + i + 3];
  59892. v2.y = positions[j + i + 4];
  59893. v2.z = positions[j + i + 5];
  59894. v3.x = positions[k + i];
  59895. v3.y = positions[k + i + 1];
  59896. v3.z = positions[k + i + 2];
  59897. v4.x = positions[k + i + 3];
  59898. v4.y = positions[k + i + 4];
  59899. v4.z = positions[k + i + 5];
  59900. // 2D slope V1V4
  59901. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59902. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59903. // facet equations :
  59904. // we compute each facet normal vector
  59905. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59906. // we compute the value d by applying the equation to v1 which belongs to the plane
  59907. // then we store the facet equation in a Vector4
  59908. v2.subtractToRef(v1, v1v2);
  59909. v3.subtractToRef(v1, v1v3);
  59910. v4.subtractToRef(v1, v1v4);
  59911. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59912. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59913. norm1.normalize();
  59914. norm2.normalize();
  59915. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59916. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59917. var quad = this._heightQuads[row * subdivisionsX + col];
  59918. quad.slope.copyFromFloats(cd, h);
  59919. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59920. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59921. }
  59922. }
  59923. return this;
  59924. };
  59925. GroundMesh.prototype.serialize = function (serializationObject) {
  59926. _super.prototype.serialize.call(this, serializationObject);
  59927. serializationObject.subdivisionsX = this._subdivisionsX;
  59928. serializationObject.subdivisionsY = this._subdivisionsY;
  59929. serializationObject.minX = this._minX;
  59930. serializationObject.maxX = this._maxX;
  59931. serializationObject.minZ = this._minZ;
  59932. serializationObject.maxZ = this._maxZ;
  59933. serializationObject.width = this._width;
  59934. serializationObject.height = this._height;
  59935. };
  59936. GroundMesh.Parse = function (parsedMesh, scene) {
  59937. var result = new GroundMesh(parsedMesh.name, scene);
  59938. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59939. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59940. result._minX = parsedMesh.minX;
  59941. result._maxX = parsedMesh.maxX;
  59942. result._minZ = parsedMesh.minZ;
  59943. result._maxZ = parsedMesh.maxZ;
  59944. result._width = parsedMesh.width;
  59945. result._height = parsedMesh.height;
  59946. return result;
  59947. };
  59948. return GroundMesh;
  59949. }(BABYLON.Mesh));
  59950. BABYLON.GroundMesh = GroundMesh;
  59951. })(BABYLON || (BABYLON = {}));
  59952. //# sourceMappingURL=babylon.groundMesh.js.map
  59953. var BABYLON;
  59954. (function (BABYLON) {
  59955. /**
  59956. * Creates an instance based on a source mesh.
  59957. */
  59958. var InstancedMesh = /** @class */ (function (_super) {
  59959. __extends(InstancedMesh, _super);
  59960. function InstancedMesh(name, source) {
  59961. var _this = _super.call(this, name, source.getScene()) || this;
  59962. source.instances.push(_this);
  59963. _this._sourceMesh = source;
  59964. _this.position.copyFrom(source.position);
  59965. _this.rotation.copyFrom(source.rotation);
  59966. _this.scaling.copyFrom(source.scaling);
  59967. if (source.rotationQuaternion) {
  59968. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59969. }
  59970. _this.infiniteDistance = source.infiniteDistance;
  59971. _this.setPivotMatrix(source.getPivotMatrix());
  59972. _this.refreshBoundingInfo();
  59973. _this._syncSubMeshes();
  59974. return _this;
  59975. }
  59976. /**
  59977. * Returns the string "InstancedMesh".
  59978. */
  59979. InstancedMesh.prototype.getClassName = function () {
  59980. return "InstancedMesh";
  59981. };
  59982. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59983. // Methods
  59984. get: function () {
  59985. return this._sourceMesh.receiveShadows;
  59986. },
  59987. enumerable: true,
  59988. configurable: true
  59989. });
  59990. Object.defineProperty(InstancedMesh.prototype, "material", {
  59991. get: function () {
  59992. return this._sourceMesh.material;
  59993. },
  59994. enumerable: true,
  59995. configurable: true
  59996. });
  59997. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59998. get: function () {
  59999. return this._sourceMesh.visibility;
  60000. },
  60001. enumerable: true,
  60002. configurable: true
  60003. });
  60004. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60005. get: function () {
  60006. return this._sourceMesh.skeleton;
  60007. },
  60008. enumerable: true,
  60009. configurable: true
  60010. });
  60011. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60012. get: function () {
  60013. return this._sourceMesh.renderingGroupId;
  60014. },
  60015. set: function (value) {
  60016. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60017. return;
  60018. }
  60019. //no-op with warning
  60020. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60021. },
  60022. enumerable: true,
  60023. configurable: true
  60024. });
  60025. /**
  60026. * Returns the total number of vertices (integer).
  60027. */
  60028. InstancedMesh.prototype.getTotalVertices = function () {
  60029. return this._sourceMesh.getTotalVertices();
  60030. };
  60031. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60032. get: function () {
  60033. return this._sourceMesh;
  60034. },
  60035. enumerable: true,
  60036. configurable: true
  60037. });
  60038. /**
  60039. * Is this node ready to be used/rendered
  60040. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60041. * @return {boolean} is it ready
  60042. */
  60043. InstancedMesh.prototype.isReady = function (completeCheck) {
  60044. if (completeCheck === void 0) { completeCheck = false; }
  60045. return this._sourceMesh.isReady(completeCheck, true);
  60046. };
  60047. /**
  60048. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60049. */
  60050. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60051. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60052. };
  60053. /**
  60054. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60055. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60056. * The `data` are either a numeric array either a Float32Array.
  60057. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60058. * 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).
  60059. * Note that a new underlying VertexBuffer object is created each call.
  60060. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60061. *
  60062. * Possible `kind` values :
  60063. * - BABYLON.VertexBuffer.PositionKind
  60064. * - BABYLON.VertexBuffer.UVKind
  60065. * - BABYLON.VertexBuffer.UV2Kind
  60066. * - BABYLON.VertexBuffer.UV3Kind
  60067. * - BABYLON.VertexBuffer.UV4Kind
  60068. * - BABYLON.VertexBuffer.UV5Kind
  60069. * - BABYLON.VertexBuffer.UV6Kind
  60070. * - BABYLON.VertexBuffer.ColorKind
  60071. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60072. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60073. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60074. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60075. *
  60076. * Returns the Mesh.
  60077. */
  60078. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60079. if (this.sourceMesh) {
  60080. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60081. }
  60082. return this.sourceMesh;
  60083. };
  60084. /**
  60085. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60086. * If the mesh has no geometry, it is simply returned as it is.
  60087. * The `data` are either a numeric array either a Float32Array.
  60088. * No new underlying VertexBuffer object is created.
  60089. * 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.
  60090. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60091. *
  60092. * Possible `kind` values :
  60093. * - BABYLON.VertexBuffer.PositionKind
  60094. * - BABYLON.VertexBuffer.UVKind
  60095. * - BABYLON.VertexBuffer.UV2Kind
  60096. * - BABYLON.VertexBuffer.UV3Kind
  60097. * - BABYLON.VertexBuffer.UV4Kind
  60098. * - BABYLON.VertexBuffer.UV5Kind
  60099. * - BABYLON.VertexBuffer.UV6Kind
  60100. * - BABYLON.VertexBuffer.ColorKind
  60101. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60102. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60103. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60104. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60105. *
  60106. * Returns the Mesh.
  60107. */
  60108. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60109. if (this.sourceMesh) {
  60110. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60111. }
  60112. return this.sourceMesh;
  60113. };
  60114. /**
  60115. * Sets the mesh indices.
  60116. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60117. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60118. * This method creates a new index buffer each call.
  60119. * Returns the Mesh.
  60120. */
  60121. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60122. if (totalVertices === void 0) { totalVertices = null; }
  60123. if (this.sourceMesh) {
  60124. this.sourceMesh.setIndices(indices, totalVertices);
  60125. }
  60126. return this.sourceMesh;
  60127. };
  60128. /**
  60129. * Boolean : True if the mesh owns the requested kind of data.
  60130. */
  60131. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60132. return this._sourceMesh.isVerticesDataPresent(kind);
  60133. };
  60134. /**
  60135. * Returns an array of indices (IndicesArray).
  60136. */
  60137. InstancedMesh.prototype.getIndices = function () {
  60138. return this._sourceMesh.getIndices();
  60139. };
  60140. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60141. get: function () {
  60142. return this._sourceMesh._positions;
  60143. },
  60144. enumerable: true,
  60145. configurable: true
  60146. });
  60147. /**
  60148. * Sets a new updated BoundingInfo to the mesh.
  60149. * Returns the mesh.
  60150. */
  60151. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60152. var meshBB = this._sourceMesh.getBoundingInfo();
  60153. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60154. this._updateBoundingInfo();
  60155. return this;
  60156. };
  60157. InstancedMesh.prototype._preActivate = function () {
  60158. if (this._currentLOD) {
  60159. this._currentLOD._preActivate();
  60160. }
  60161. return this;
  60162. };
  60163. InstancedMesh.prototype._activate = function (renderId) {
  60164. if (this._currentLOD) {
  60165. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60166. }
  60167. return this;
  60168. };
  60169. /**
  60170. * Returns the current associated LOD AbstractMesh.
  60171. */
  60172. InstancedMesh.prototype.getLOD = function (camera) {
  60173. if (!camera) {
  60174. return this;
  60175. }
  60176. var boundingInfo = this.getBoundingInfo();
  60177. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60178. if (this._currentLOD === this.sourceMesh) {
  60179. return this;
  60180. }
  60181. return this._currentLOD;
  60182. };
  60183. InstancedMesh.prototype._syncSubMeshes = function () {
  60184. this.releaseSubMeshes();
  60185. if (this._sourceMesh.subMeshes) {
  60186. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60187. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60188. }
  60189. }
  60190. return this;
  60191. };
  60192. InstancedMesh.prototype._generatePointsArray = function () {
  60193. return this._sourceMesh._generatePointsArray();
  60194. };
  60195. /**
  60196. * Creates a new InstancedMesh from the current mesh.
  60197. * - name (string) : the cloned mesh name
  60198. * - newParent (optional Node) : the optional Node to parent the clone to.
  60199. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60200. *
  60201. * Returns the clone.
  60202. */
  60203. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60204. var result = this._sourceMesh.createInstance(name);
  60205. // Deep copy
  60206. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60207. // Bounding info
  60208. this.refreshBoundingInfo();
  60209. // Parent
  60210. if (newParent) {
  60211. result.parent = newParent;
  60212. }
  60213. if (!doNotCloneChildren) {
  60214. // Children
  60215. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60216. var mesh = this.getScene().meshes[index];
  60217. if (mesh.parent === this) {
  60218. mesh.clone(mesh.name, result);
  60219. }
  60220. }
  60221. }
  60222. result.computeWorldMatrix(true);
  60223. return result;
  60224. };
  60225. /**
  60226. * Disposes the InstancedMesh.
  60227. * Returns nothing.
  60228. */
  60229. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60230. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60231. // Remove from mesh
  60232. var index = this._sourceMesh.instances.indexOf(this);
  60233. this._sourceMesh.instances.splice(index, 1);
  60234. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60235. };
  60236. return InstancedMesh;
  60237. }(BABYLON.AbstractMesh));
  60238. BABYLON.InstancedMesh = InstancedMesh;
  60239. })(BABYLON || (BABYLON = {}));
  60240. //# sourceMappingURL=babylon.instancedMesh.js.map
  60241. var BABYLON;
  60242. (function (BABYLON) {
  60243. var LinesMesh = /** @class */ (function (_super) {
  60244. __extends(LinesMesh, _super);
  60245. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60246. if (scene === void 0) { scene = null; }
  60247. if (parent === void 0) { parent = null; }
  60248. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60249. _this.useVertexColor = useVertexColor;
  60250. _this.useVertexAlpha = useVertexAlpha;
  60251. _this.color = new BABYLON.Color3(1, 1, 1);
  60252. _this.alpha = 1;
  60253. if (source) {
  60254. _this.color = source.color.clone();
  60255. _this.alpha = source.alpha;
  60256. _this.useVertexColor = source.useVertexColor;
  60257. _this.useVertexAlpha = source.useVertexAlpha;
  60258. }
  60259. _this._intersectionThreshold = 0.1;
  60260. var defines = [];
  60261. var options = {
  60262. attributes: [BABYLON.VertexBuffer.PositionKind],
  60263. uniforms: ["world", "viewProjection"],
  60264. needAlphaBlending: true,
  60265. defines: defines
  60266. };
  60267. if (useVertexAlpha === false) {
  60268. options.needAlphaBlending = false;
  60269. }
  60270. if (!useVertexColor) {
  60271. options.uniforms.push("color");
  60272. }
  60273. else {
  60274. options.defines.push("#define VERTEXCOLOR");
  60275. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60276. }
  60277. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60278. return _this;
  60279. }
  60280. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60281. /**
  60282. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60283. * This margin is expressed in world space coordinates, so its value may vary.
  60284. * Default value is 0.1
  60285. * @returns the intersection Threshold value.
  60286. */
  60287. get: function () {
  60288. return this._intersectionThreshold;
  60289. },
  60290. /**
  60291. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60292. * This margin is expressed in world space coordinates, so its value may vary.
  60293. * @param value the new threshold to apply
  60294. */
  60295. set: function (value) {
  60296. if (this._intersectionThreshold === value) {
  60297. return;
  60298. }
  60299. this._intersectionThreshold = value;
  60300. if (this.geometry) {
  60301. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60302. }
  60303. },
  60304. enumerable: true,
  60305. configurable: true
  60306. });
  60307. /**
  60308. * Returns the string "LineMesh"
  60309. */
  60310. LinesMesh.prototype.getClassName = function () {
  60311. return "LinesMesh";
  60312. };
  60313. Object.defineProperty(LinesMesh.prototype, "material", {
  60314. get: function () {
  60315. return this._colorShader;
  60316. },
  60317. set: function (value) {
  60318. // Do nothing
  60319. },
  60320. enumerable: true,
  60321. configurable: true
  60322. });
  60323. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60324. get: function () {
  60325. return false;
  60326. },
  60327. enumerable: true,
  60328. configurable: true
  60329. });
  60330. LinesMesh.prototype.createInstance = function (name) {
  60331. throw new Error("LinesMeshes do not support createInstance.");
  60332. };
  60333. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60334. if (!this._geometry) {
  60335. return this;
  60336. }
  60337. // VBOs
  60338. this._geometry._bind(this._colorShader.getEffect());
  60339. // Color
  60340. if (!this.useVertexColor) {
  60341. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60342. }
  60343. return this;
  60344. };
  60345. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60346. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60347. return this;
  60348. }
  60349. var engine = this.getScene().getEngine();
  60350. // Draw order
  60351. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60352. return this;
  60353. };
  60354. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60355. this._colorShader.dispose();
  60356. _super.prototype.dispose.call(this, doNotRecurse);
  60357. };
  60358. /**
  60359. * Returns a new LineMesh object cloned from the current one.
  60360. */
  60361. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60362. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60363. };
  60364. return LinesMesh;
  60365. }(BABYLON.Mesh));
  60366. BABYLON.LinesMesh = LinesMesh;
  60367. })(BABYLON || (BABYLON = {}));
  60368. //# sourceMappingURL=babylon.linesMesh.js.map
  60369. var BABYLON;
  60370. (function (BABYLON) {
  60371. /**
  60372. * Class containing static functions to help procedurally build meshes
  60373. */
  60374. var MeshBuilder = /** @class */ (function () {
  60375. function MeshBuilder() {
  60376. }
  60377. MeshBuilder.updateSideOrientation = function (orientation) {
  60378. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60379. return BABYLON.Mesh.DOUBLESIDE;
  60380. }
  60381. if (orientation === undefined || orientation === null) {
  60382. return BABYLON.Mesh.FRONTSIDE;
  60383. }
  60384. return orientation;
  60385. };
  60386. /**
  60387. * Creates a box mesh
  60388. * * The parameter `size` sets the size (float) of each box side (default 1)
  60389. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60390. * * 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)
  60391. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60392. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60393. * * 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
  60394. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60395. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60396. * @param name defines the name of the mesh
  60397. * @param options defines the options used to create the mesh
  60398. * @param scene defines the hosting scene
  60399. * @returns the box mesh
  60400. */
  60401. MeshBuilder.CreateBox = function (name, options, scene) {
  60402. if (scene === void 0) { scene = null; }
  60403. var box = new BABYLON.Mesh(name, scene);
  60404. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60405. box._originalBuilderSideOrientation = options.sideOrientation;
  60406. var vertexData = BABYLON.VertexData.CreateBox(options);
  60407. vertexData.applyToMesh(box, options.updatable);
  60408. return box;
  60409. };
  60410. /**
  60411. * Creates a sphere mesh
  60412. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60413. * * 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`)
  60414. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60415. * * 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
  60416. * * 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)
  60417. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60418. * * 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
  60419. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60420. * @param name defines the name of the mesh
  60421. * @param options defines the options used to create the mesh
  60422. * @param scene defines the hosting scene
  60423. * @returns the sphere mesh
  60424. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60425. */
  60426. MeshBuilder.CreateSphere = function (name, options, scene) {
  60427. var sphere = new BABYLON.Mesh(name, scene);
  60428. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60429. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60430. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60431. vertexData.applyToMesh(sphere, options.updatable);
  60432. return sphere;
  60433. };
  60434. /**
  60435. * Creates a plane polygonal mesh. By default, this is a disc
  60436. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60437. * * 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
  60438. * * 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
  60439. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60440. * * 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
  60441. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60442. * @param name defines the name of the mesh
  60443. * @param options defines the options used to create the mesh
  60444. * @param scene defines the hosting scene
  60445. * @returns the plane polygonal mesh
  60446. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60447. */
  60448. MeshBuilder.CreateDisc = function (name, options, scene) {
  60449. if (scene === void 0) { scene = null; }
  60450. var disc = new BABYLON.Mesh(name, scene);
  60451. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60452. disc._originalBuilderSideOrientation = options.sideOrientation;
  60453. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60454. vertexData.applyToMesh(disc, options.updatable);
  60455. return disc;
  60456. };
  60457. /**
  60458. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60459. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60460. * * 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`)
  60461. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60462. * * 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
  60463. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60464. * * 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
  60465. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60466. * @param name defines the name of the mesh
  60467. * @param options defines the options used to create the mesh
  60468. * @param scene defines the hosting scene
  60469. * @returns the icosahedron mesh
  60470. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60471. */
  60472. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60473. var sphere = new BABYLON.Mesh(name, scene);
  60474. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60475. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60476. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60477. vertexData.applyToMesh(sphere, options.updatable);
  60478. return sphere;
  60479. };
  60480. ;
  60481. /**
  60482. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60483. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60484. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60485. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60486. * * 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
  60487. * * 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
  60488. * * 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
  60489. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60490. * * 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
  60491. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60492. * * 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
  60493. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60494. * * 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
  60495. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60496. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60497. * @param name defines the name of the mesh
  60498. * @param options defines the options used to create the mesh
  60499. * @param scene defines the hosting scene
  60500. * @returns the ribbon mesh
  60501. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60502. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60503. */
  60504. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60505. if (scene === void 0) { scene = null; }
  60506. var pathArray = options.pathArray;
  60507. var closeArray = options.closeArray;
  60508. var closePath = options.closePath;
  60509. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60510. var instance = options.instance;
  60511. var updatable = options.updatable;
  60512. if (instance) { // existing ribbon instance update
  60513. // positionFunction : ribbon case
  60514. // only pathArray and sideOrientation parameters are taken into account for positions update
  60515. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60516. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60517. var positionFunction = function (positions) {
  60518. var minlg = pathArray[0].length;
  60519. var i = 0;
  60520. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60521. for (var si = 1; si <= ns; si++) {
  60522. for (var p = 0; p < pathArray.length; p++) {
  60523. var path = pathArray[p];
  60524. var l = path.length;
  60525. minlg = (minlg < l) ? minlg : l;
  60526. var j = 0;
  60527. while (j < minlg) {
  60528. positions[i] = path[j].x;
  60529. positions[i + 1] = path[j].y;
  60530. positions[i + 2] = path[j].z;
  60531. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60532. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60533. }
  60534. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60535. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60536. }
  60537. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60538. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60539. }
  60540. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60541. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60542. }
  60543. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60544. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60545. }
  60546. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60547. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60548. }
  60549. j++;
  60550. i += 3;
  60551. }
  60552. if (instance._closePath) {
  60553. positions[i] = path[0].x;
  60554. positions[i + 1] = path[0].y;
  60555. positions[i + 2] = path[0].z;
  60556. i += 3;
  60557. }
  60558. }
  60559. }
  60560. };
  60561. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60562. positionFunction(positions);
  60563. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60564. instance._boundingInfo.update(instance._worldMatrix);
  60565. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60566. if (options.colors) {
  60567. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60568. for (var c = 0; c < options.colors.length; c++) {
  60569. colors[c * 4] = options.colors[c].r;
  60570. colors[c * 4 + 1] = options.colors[c].g;
  60571. colors[c * 4 + 2] = options.colors[c].b;
  60572. colors[c * 4 + 3] = options.colors[c].a;
  60573. }
  60574. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60575. }
  60576. if (options.uvs) {
  60577. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60578. for (var i = 0; i < options.uvs.length; i++) {
  60579. uvs[i * 2] = options.uvs[i].x;
  60580. uvs[i * 2 + 1] = options.uvs[i].y;
  60581. }
  60582. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60583. }
  60584. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60585. var indices = instance.getIndices();
  60586. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60587. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60588. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60589. if (instance._closePath) {
  60590. var indexFirst = 0;
  60591. var indexLast = 0;
  60592. for (var p = 0; p < pathArray.length; p++) {
  60593. indexFirst = instance._idx[p] * 3;
  60594. if (p + 1 < pathArray.length) {
  60595. indexLast = (instance._idx[p + 1] - 1) * 3;
  60596. }
  60597. else {
  60598. indexLast = normals.length - 3;
  60599. }
  60600. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60601. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60602. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60603. normals[indexLast] = normals[indexFirst];
  60604. normals[indexLast + 1] = normals[indexFirst + 1];
  60605. normals[indexLast + 2] = normals[indexFirst + 2];
  60606. }
  60607. }
  60608. if (!(instance.areNormalsFrozen)) {
  60609. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60610. }
  60611. }
  60612. return instance;
  60613. }
  60614. else { // new ribbon creation
  60615. var ribbon = new BABYLON.Mesh(name, scene);
  60616. ribbon._originalBuilderSideOrientation = sideOrientation;
  60617. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60618. if (closePath) {
  60619. ribbon._idx = vertexData._idx;
  60620. }
  60621. ribbon._closePath = closePath;
  60622. ribbon._closeArray = closeArray;
  60623. vertexData.applyToMesh(ribbon, updatable);
  60624. return ribbon;
  60625. }
  60626. };
  60627. /**
  60628. * Creates a cylinder or a cone mesh
  60629. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60630. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60631. * * 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.
  60632. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60633. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60634. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60635. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60636. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60637. * * 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).
  60638. * * 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
  60639. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60640. * * 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
  60641. * * 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.
  60642. * * If `enclose` is false, a ring surface is one element.
  60643. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60644. * * 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
  60645. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60646. * * 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
  60647. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60648. * @param name defines the name of the mesh
  60649. * @param options defines the options used to create the mesh
  60650. * @param scene defines the hosting scene
  60651. * @returns the cylinder mesh
  60652. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60653. */
  60654. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60655. var cylinder = new BABYLON.Mesh(name, scene);
  60656. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60657. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60658. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60659. vertexData.applyToMesh(cylinder, options.updatable);
  60660. return cylinder;
  60661. };
  60662. /**
  60663. * Creates a torus mesh
  60664. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60665. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60666. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60667. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60668. * * 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
  60669. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60670. * @param name defines the name of the mesh
  60671. * @param options defines the options used to create the mesh
  60672. * @param scene defines the hosting scene
  60673. * @returns the torus mesh
  60674. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60675. */
  60676. MeshBuilder.CreateTorus = function (name, options, scene) {
  60677. var torus = new BABYLON.Mesh(name, scene);
  60678. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60679. torus._originalBuilderSideOrientation = options.sideOrientation;
  60680. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60681. vertexData.applyToMesh(torus, options.updatable);
  60682. return torus;
  60683. };
  60684. /**
  60685. * Creates a torus knot mesh
  60686. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60687. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60688. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60689. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60690. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60691. * * 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
  60692. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60693. * @param name defines the name of the mesh
  60694. * @param options defines the options used to create the mesh
  60695. * @param scene defines the hosting scene
  60696. * @returns the torus knot mesh
  60697. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60698. */
  60699. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60700. var torusKnot = new BABYLON.Mesh(name, scene);
  60701. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60702. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60703. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60704. vertexData.applyToMesh(torusKnot, options.updatable);
  60705. return torusKnot;
  60706. };
  60707. /**
  60708. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60709. * * 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
  60710. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60711. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60712. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60713. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60714. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60715. * * 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
  60716. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60717. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60718. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60719. * @param name defines the name of the new line system
  60720. * @param options defines the options used to create the line system
  60721. * @param scene defines the hosting scene
  60722. * @returns a new line system mesh
  60723. */
  60724. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60725. var instance = options.instance;
  60726. var lines = options.lines;
  60727. var colors = options.colors;
  60728. if (instance) { // lines update
  60729. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60730. var vertexColor;
  60731. var lineColors;
  60732. if (colors) {
  60733. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60734. }
  60735. var i = 0;
  60736. var c = 0;
  60737. for (var l = 0; l < lines.length; l++) {
  60738. var points = lines[l];
  60739. for (var p = 0; p < points.length; p++) {
  60740. positions[i] = points[p].x;
  60741. positions[i + 1] = points[p].y;
  60742. positions[i + 2] = points[p].z;
  60743. if (colors && vertexColor) {
  60744. lineColors = colors[l];
  60745. vertexColor[c] = lineColors[p].r;
  60746. vertexColor[c + 1] = lineColors[p].g;
  60747. vertexColor[c + 2] = lineColors[p].b;
  60748. vertexColor[c + 3] = lineColors[p].a;
  60749. c += 4;
  60750. }
  60751. i += 3;
  60752. }
  60753. }
  60754. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60755. if (colors && vertexColor) {
  60756. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60757. }
  60758. return instance;
  60759. }
  60760. // line system creation
  60761. var useVertexColor = (colors) ? true : false;
  60762. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60763. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60764. vertexData.applyToMesh(lineSystem, options.updatable);
  60765. return lineSystem;
  60766. };
  60767. /**
  60768. * Creates a line mesh
  60769. * 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
  60770. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60771. * * The parameter `points` is an array successive Vector3
  60772. * * 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
  60773. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60774. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60775. * * When updating an instance, remember that only point positions can change, not the number of points
  60776. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60777. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60778. * @param name defines the name of the new line system
  60779. * @param options defines the options used to create the line system
  60780. * @param scene defines the hosting scene
  60781. * @returns a new line mesh
  60782. */
  60783. MeshBuilder.CreateLines = function (name, options, scene) {
  60784. if (scene === void 0) { scene = null; }
  60785. var colors = (options.colors) ? [options.colors] : null;
  60786. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60787. return lines;
  60788. };
  60789. /**
  60790. * Creates a dashed line mesh
  60791. * * 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
  60792. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60793. * * The parameter `points` is an array successive Vector3
  60794. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60795. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60796. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60797. * * 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
  60798. * * When updating an instance, remember that only point positions can change, not the number of points
  60799. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60800. * @param name defines the name of the mesh
  60801. * @param options defines the options used to create the mesh
  60802. * @param scene defines the hosting scene
  60803. * @returns the dashed line mesh
  60804. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60805. */
  60806. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60807. if (scene === void 0) { scene = null; }
  60808. var points = options.points;
  60809. var instance = options.instance;
  60810. var gapSize = options.gapSize || 1;
  60811. var dashSize = options.dashSize || 3;
  60812. if (instance) { // dashed lines update
  60813. var positionFunction = function (positions) {
  60814. var curvect = BABYLON.Vector3.Zero();
  60815. var nbSeg = positions.length / 6;
  60816. var lg = 0;
  60817. var nb = 0;
  60818. var shft = 0;
  60819. var dashshft = 0;
  60820. var curshft = 0;
  60821. var p = 0;
  60822. var i = 0;
  60823. var j = 0;
  60824. for (i = 0; i < points.length - 1; i++) {
  60825. points[i + 1].subtractToRef(points[i], curvect);
  60826. lg += curvect.length();
  60827. }
  60828. shft = lg / nbSeg;
  60829. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60830. for (i = 0; i < points.length - 1; i++) {
  60831. points[i + 1].subtractToRef(points[i], curvect);
  60832. nb = Math.floor(curvect.length() / shft);
  60833. curvect.normalize();
  60834. j = 0;
  60835. while (j < nb && p < positions.length) {
  60836. curshft = shft * j;
  60837. positions[p] = points[i].x + curshft * curvect.x;
  60838. positions[p + 1] = points[i].y + curshft * curvect.y;
  60839. positions[p + 2] = points[i].z + curshft * curvect.z;
  60840. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60841. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60842. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60843. p += 6;
  60844. j++;
  60845. }
  60846. }
  60847. while (p < positions.length) {
  60848. positions[p] = points[i].x;
  60849. positions[p + 1] = points[i].y;
  60850. positions[p + 2] = points[i].z;
  60851. p += 3;
  60852. }
  60853. };
  60854. instance.updateMeshPositions(positionFunction, false);
  60855. return instance;
  60856. }
  60857. // dashed lines creation
  60858. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60859. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60860. vertexData.applyToMesh(dashedLines, options.updatable);
  60861. dashedLines.dashSize = dashSize;
  60862. dashedLines.gapSize = gapSize;
  60863. return dashedLines;
  60864. };
  60865. /**
  60866. * 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.
  60867. * * 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.
  60868. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60869. * * 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.
  60870. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60871. * * 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
  60872. * * 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
  60873. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60874. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60875. * * 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
  60876. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60877. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60878. * @param name defines the name of the mesh
  60879. * @param options defines the options used to create the mesh
  60880. * @param scene defines the hosting scene
  60881. * @returns the extruded shape mesh
  60882. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60883. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60884. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60885. */
  60886. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60887. if (scene === void 0) { scene = null; }
  60888. var path = options.path;
  60889. var shape = options.shape;
  60890. var scale = options.scale || 1;
  60891. var rotation = options.rotation || 0;
  60892. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60893. var updatable = options.updatable;
  60894. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60895. var instance = options.instance || null;
  60896. var invertUV = options.invertUV || false;
  60897. 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);
  60898. };
  60899. /**
  60900. * Creates an custom extruded shape mesh.
  60901. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60902. * * 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.
  60903. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60904. * * 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
  60905. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60906. * * 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
  60907. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60908. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60909. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60910. * * 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
  60911. * * 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
  60912. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60913. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60914. * * 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
  60915. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60916. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60917. * @param name defines the name of the mesh
  60918. * @param options defines the options used to create the mesh
  60919. * @param scene defines the hosting scene
  60920. * @returns the custom extruded shape mesh
  60921. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60922. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60923. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60924. */
  60925. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60926. var path = options.path;
  60927. var shape = options.shape;
  60928. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60929. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60930. var ribbonCloseArray = options.ribbonCloseArray || false;
  60931. var ribbonClosePath = options.ribbonClosePath || false;
  60932. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60933. var updatable = options.updatable;
  60934. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60935. var instance = options.instance;
  60936. var invertUV = options.invertUV || false;
  60937. 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);
  60938. };
  60939. /**
  60940. * Creates lathe mesh.
  60941. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60942. * * 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
  60943. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60944. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60945. * * 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
  60946. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60947. * * 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
  60948. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60949. * * 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
  60950. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60951. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60952. * @param name defines the name of the mesh
  60953. * @param options defines the options used to create the mesh
  60954. * @param scene defines the hosting scene
  60955. * @returns the lathe mesh
  60956. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60957. */
  60958. MeshBuilder.CreateLathe = function (name, options, scene) {
  60959. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60960. var closed = (options.closed === undefined) ? true : options.closed;
  60961. var shape = options.shape;
  60962. var radius = options.radius || 1;
  60963. var tessellation = options.tessellation || 64;
  60964. var updatable = options.updatable;
  60965. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60966. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60967. var pi2 = Math.PI * 2;
  60968. var paths = new Array();
  60969. var invertUV = options.invertUV || false;
  60970. var i = 0;
  60971. var p = 0;
  60972. var step = pi2 / tessellation * arc;
  60973. var rotated;
  60974. var path = new Array();
  60975. ;
  60976. for (i = 0; i <= tessellation; i++) {
  60977. var path = [];
  60978. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60979. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60980. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60981. }
  60982. for (p = 0; p < shape.length; p++) {
  60983. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60984. path.push(rotated);
  60985. }
  60986. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60987. 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));
  60988. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60989. }
  60990. paths.push(path);
  60991. }
  60992. // lathe ribbon
  60993. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60994. return lathe;
  60995. };
  60996. /**
  60997. * Creates a plane mesh
  60998. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60999. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61000. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61001. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61002. * * 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
  61003. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61004. * @param name defines the name of the mesh
  61005. * @param options defines the options used to create the mesh
  61006. * @param scene defines the hosting scene
  61007. * @returns the plane mesh
  61008. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61009. */
  61010. MeshBuilder.CreatePlane = function (name, options, scene) {
  61011. var plane = new BABYLON.Mesh(name, scene);
  61012. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61013. plane._originalBuilderSideOrientation = options.sideOrientation;
  61014. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61015. vertexData.applyToMesh(plane, options.updatable);
  61016. if (options.sourcePlane) {
  61017. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61018. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61019. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61020. plane.rotate(vectorProduct, product);
  61021. }
  61022. return plane;
  61023. };
  61024. /**
  61025. * Creates a ground mesh
  61026. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61027. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61028. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61029. * @param name defines the name of the mesh
  61030. * @param options defines the options used to create the mesh
  61031. * @param scene defines the hosting scene
  61032. * @returns the ground mesh
  61033. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61034. */
  61035. MeshBuilder.CreateGround = function (name, options, scene) {
  61036. var ground = new BABYLON.GroundMesh(name, scene);
  61037. ground._setReady(false);
  61038. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61039. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61040. ground._width = options.width || 1;
  61041. ground._height = options.height || 1;
  61042. ground._maxX = ground._width / 2;
  61043. ground._maxZ = ground._height / 2;
  61044. ground._minX = -ground._maxX;
  61045. ground._minZ = -ground._maxZ;
  61046. var vertexData = BABYLON.VertexData.CreateGround(options);
  61047. vertexData.applyToMesh(ground, options.updatable);
  61048. ground._setReady(true);
  61049. return ground;
  61050. };
  61051. /**
  61052. * Creates a tiled ground mesh
  61053. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61054. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61055. * * 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
  61056. * * 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
  61057. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61058. * @param name defines the name of the mesh
  61059. * @param options defines the options used to create the mesh
  61060. * @param scene defines the hosting scene
  61061. * @returns the tiled ground mesh
  61062. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61063. */
  61064. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61065. var tiledGround = new BABYLON.Mesh(name, scene);
  61066. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61067. vertexData.applyToMesh(tiledGround, options.updatable);
  61068. return tiledGround;
  61069. };
  61070. /**
  61071. * Creates a ground mesh from a height map
  61072. * * The parameter `url` sets the URL of the height map image resource.
  61073. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61074. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61075. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61076. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61077. * * 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.
  61078. * * 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).
  61079. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61080. * @param name defines the name of the mesh
  61081. * @param url defines the url to the height map
  61082. * @param options defines the options used to create the mesh
  61083. * @param scene defines the hosting scene
  61084. * @returns the ground mesh
  61085. * @see http://doc.babylonjs.com/babylon101/height_map
  61086. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61087. */
  61088. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61089. var width = options.width || 10.0;
  61090. var height = options.height || 10.0;
  61091. var subdivisions = options.subdivisions || 1 | 0;
  61092. var minHeight = options.minHeight || 0.0;
  61093. var maxHeight = options.maxHeight || 1.0;
  61094. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61095. var updatable = options.updatable;
  61096. var onReady = options.onReady;
  61097. var ground = new BABYLON.GroundMesh(name, scene);
  61098. ground._subdivisionsX = subdivisions;
  61099. ground._subdivisionsY = subdivisions;
  61100. ground._width = width;
  61101. ground._height = height;
  61102. ground._maxX = ground._width / 2.0;
  61103. ground._maxZ = ground._height / 2.0;
  61104. ground._minX = -ground._maxX;
  61105. ground._minZ = -ground._maxZ;
  61106. ground._setReady(false);
  61107. var onload = function (img) {
  61108. // Getting height map data
  61109. var canvas = document.createElement("canvas");
  61110. var context = canvas.getContext("2d");
  61111. if (!context) {
  61112. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61113. }
  61114. if (scene.isDisposed) {
  61115. return;
  61116. }
  61117. var bufferWidth = img.width;
  61118. var bufferHeight = img.height;
  61119. canvas.width = bufferWidth;
  61120. canvas.height = bufferHeight;
  61121. context.drawImage(img, 0, 0);
  61122. // Create VertexData from map data
  61123. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61124. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61125. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61126. width: width, height: height,
  61127. subdivisions: subdivisions,
  61128. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61129. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61130. });
  61131. vertexData.applyToMesh(ground, updatable);
  61132. //execute ready callback, if set
  61133. if (onReady) {
  61134. onReady(ground);
  61135. }
  61136. ground._setReady(true);
  61137. };
  61138. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61139. return ground;
  61140. };
  61141. /**
  61142. * Creates a polygon mesh
  61143. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61144. * * 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
  61145. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61146. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61147. * * 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)
  61148. * * Remember you can only change the shape positions, not their number when updating a polygon
  61149. * @param name defines the name of the mesh
  61150. * @param options defines the options used to create the mesh
  61151. * @param scene defines the hosting scene
  61152. * @returns the polygon mesh
  61153. */
  61154. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61155. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61156. var shape = options.shape;
  61157. var holes = options.holes || [];
  61158. var depth = options.depth || 0;
  61159. var contours = [];
  61160. var hole = [];
  61161. for (var i = 0; i < shape.length; i++) {
  61162. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61163. }
  61164. var epsilon = 0.00000001;
  61165. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61166. contours.pop();
  61167. }
  61168. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61169. for (var hNb = 0; hNb < holes.length; hNb++) {
  61170. hole = [];
  61171. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61172. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61173. }
  61174. polygonTriangulation.addHole(hole);
  61175. }
  61176. var polygon = polygonTriangulation.build(options.updatable, depth);
  61177. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61178. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61179. vertexData.applyToMesh(polygon, options.updatable);
  61180. return polygon;
  61181. };
  61182. ;
  61183. /**
  61184. * Creates an extruded polygon mesh, with depth in the Y direction.
  61185. * * 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)
  61186. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61187. * @param name defines the name of the mesh
  61188. * @param options defines the options used to create the mesh
  61189. * @param scene defines the hosting scene
  61190. * @returns the polygon mesh
  61191. */
  61192. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61193. return MeshBuilder.CreatePolygon(name, options, scene);
  61194. };
  61195. ;
  61196. /**
  61197. * Creates a tube mesh.
  61198. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61199. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61200. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61201. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61202. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61203. * * 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)
  61204. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61205. * * 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
  61206. * * 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
  61207. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61208. * * 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
  61209. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61210. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61211. * @param name defines the name of the mesh
  61212. * @param options defines the options used to create the mesh
  61213. * @param scene defines the hosting scene
  61214. * @returns the tube mesh
  61215. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61216. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61217. */
  61218. MeshBuilder.CreateTube = function (name, options, scene) {
  61219. var path = options.path;
  61220. var instance = options.instance;
  61221. var radius = 1.0;
  61222. if (instance) {
  61223. radius = instance.radius;
  61224. }
  61225. if (options.radius !== undefined) {
  61226. radius = options.radius;
  61227. }
  61228. ;
  61229. var tessellation = options.tessellation || 64 | 0;
  61230. var radiusFunction = options.radiusFunction || null;
  61231. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61232. var invertUV = options.invertUV || false;
  61233. var updatable = options.updatable;
  61234. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61235. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61236. // tube geometry
  61237. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61238. var tangents = path3D.getTangents();
  61239. var normals = path3D.getNormals();
  61240. var distances = path3D.getDistances();
  61241. var pi2 = Math.PI * 2;
  61242. var step = pi2 / tessellation * arc;
  61243. var returnRadius = function () { return radius; };
  61244. var radiusFunctionFinal = radiusFunction || returnRadius;
  61245. var circlePath;
  61246. var rad;
  61247. var normal;
  61248. var rotated;
  61249. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61250. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61251. for (var i = 0; i < path.length; i++) {
  61252. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61253. circlePath = Array(); // current circle array
  61254. normal = normals[i]; // current normal
  61255. for (var t = 0; t < tessellation; t++) {
  61256. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61257. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61258. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61259. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61260. circlePath[t] = rotated;
  61261. }
  61262. circlePaths[index] = circlePath;
  61263. index++;
  61264. }
  61265. // cap
  61266. var capPath = function (nbPoints, pathIndex) {
  61267. var pointCap = Array();
  61268. for (var i = 0; i < nbPoints; i++) {
  61269. pointCap.push(path[pathIndex]);
  61270. }
  61271. return pointCap;
  61272. };
  61273. switch (cap) {
  61274. case BABYLON.Mesh.NO_CAP:
  61275. break;
  61276. case BABYLON.Mesh.CAP_START:
  61277. circlePaths[0] = capPath(tessellation, 0);
  61278. circlePaths[1] = circlePaths[2].slice(0);
  61279. break;
  61280. case BABYLON.Mesh.CAP_END:
  61281. circlePaths[index] = circlePaths[index - 1].slice(0);
  61282. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61283. break;
  61284. case BABYLON.Mesh.CAP_ALL:
  61285. circlePaths[0] = capPath(tessellation, 0);
  61286. circlePaths[1] = circlePaths[2].slice(0);
  61287. circlePaths[index] = circlePaths[index - 1].slice(0);
  61288. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61289. break;
  61290. default:
  61291. break;
  61292. }
  61293. return circlePaths;
  61294. };
  61295. var path3D;
  61296. var pathArray;
  61297. if (instance) { // tube update
  61298. var arc = options.arc || instance.arc;
  61299. path3D = (instance.path3D).update(path);
  61300. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61301. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61302. instance.path3D = path3D;
  61303. instance.pathArray = pathArray;
  61304. instance.arc = arc;
  61305. instance.radius = radius;
  61306. return instance;
  61307. }
  61308. // tube creation
  61309. path3D = new BABYLON.Path3D(path);
  61310. var newPathArray = new Array();
  61311. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61312. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61313. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61314. tube.pathArray = pathArray;
  61315. tube.path3D = path3D;
  61316. tube.tessellation = tessellation;
  61317. tube.cap = cap;
  61318. tube.arc = options.arc;
  61319. tube.radius = radius;
  61320. return tube;
  61321. };
  61322. /**
  61323. * Creates a polyhedron mesh
  61324. * * 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
  61325. * * The parameter `size` (positive float, default 1) sets the polygon size
  61326. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61327. * * 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`
  61328. * * 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
  61329. * * 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)`)
  61330. * * 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
  61331. * * 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
  61332. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61333. * * 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
  61334. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61335. * @param name defines the name of the mesh
  61336. * @param options defines the options used to create the mesh
  61337. * @param scene defines the hosting scene
  61338. * @returns the polyhedron mesh
  61339. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61340. */
  61341. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61342. var polyhedron = new BABYLON.Mesh(name, scene);
  61343. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61344. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61345. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61346. vertexData.applyToMesh(polyhedron, options.updatable);
  61347. return polyhedron;
  61348. };
  61349. /**
  61350. * Creates a decal mesh.
  61351. * 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
  61352. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61353. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61354. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61355. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61356. * @param name defines the name of the mesh
  61357. * @param sourceMesh defines the mesh where the decal must be applied
  61358. * @param options defines the options used to create the mesh
  61359. * @param scene defines the hosting scene
  61360. * @returns the decal mesh
  61361. * @see http://doc.babylonjs.com/how_to/decals
  61362. */
  61363. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61364. var indices = sourceMesh.getIndices();
  61365. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61366. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61367. var position = options.position || BABYLON.Vector3.Zero();
  61368. var normal = options.normal || BABYLON.Vector3.Up();
  61369. var size = options.size || BABYLON.Vector3.One();
  61370. var angle = options.angle || 0;
  61371. // Getting correct rotation
  61372. if (!normal) {
  61373. var target = new BABYLON.Vector3(0, 0, 1);
  61374. var camera = sourceMesh.getScene().activeCamera;
  61375. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61376. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61377. }
  61378. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61379. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61380. var pitch = Math.atan2(normal.y, len);
  61381. // Matrix
  61382. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61383. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61384. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61385. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61386. var vertexData = new BABYLON.VertexData();
  61387. vertexData.indices = [];
  61388. vertexData.positions = [];
  61389. vertexData.normals = [];
  61390. vertexData.uvs = [];
  61391. var currentVertexDataIndex = 0;
  61392. var extractDecalVector3 = function (indexId) {
  61393. var result = new BABYLON.PositionNormalVertex();
  61394. if (!indices || !positions || !normals) {
  61395. return result;
  61396. }
  61397. var vertexId = indices[indexId];
  61398. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61399. // Send vector to decal local world
  61400. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61401. // Get normal
  61402. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61403. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61404. return result;
  61405. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61406. var clip = function (vertices, axis) {
  61407. if (vertices.length === 0) {
  61408. return vertices;
  61409. }
  61410. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61411. var clipVertices = function (v0, v1) {
  61412. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61413. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61414. };
  61415. var result = new Array();
  61416. for (var index = 0; index < vertices.length; index += 3) {
  61417. var v1Out;
  61418. var v2Out;
  61419. var v3Out;
  61420. var total = 0;
  61421. var nV1 = null;
  61422. var nV2 = null;
  61423. var nV3 = null;
  61424. var nV4 = null;
  61425. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61426. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61427. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61428. v1Out = d1 > 0;
  61429. v2Out = d2 > 0;
  61430. v3Out = d3 > 0;
  61431. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61432. switch (total) {
  61433. case 0:
  61434. result.push(vertices[index]);
  61435. result.push(vertices[index + 1]);
  61436. result.push(vertices[index + 2]);
  61437. break;
  61438. case 1:
  61439. if (v1Out) {
  61440. nV1 = vertices[index + 1];
  61441. nV2 = vertices[index + 2];
  61442. nV3 = clipVertices(vertices[index], nV1);
  61443. nV4 = clipVertices(vertices[index], nV2);
  61444. }
  61445. if (v2Out) {
  61446. nV1 = vertices[index];
  61447. nV2 = vertices[index + 2];
  61448. nV3 = clipVertices(vertices[index + 1], nV1);
  61449. nV4 = clipVertices(vertices[index + 1], nV2);
  61450. result.push(nV3);
  61451. result.push(nV2.clone());
  61452. result.push(nV1.clone());
  61453. result.push(nV2.clone());
  61454. result.push(nV3.clone());
  61455. result.push(nV4);
  61456. break;
  61457. }
  61458. if (v3Out) {
  61459. nV1 = vertices[index];
  61460. nV2 = vertices[index + 1];
  61461. nV3 = clipVertices(vertices[index + 2], nV1);
  61462. nV4 = clipVertices(vertices[index + 2], nV2);
  61463. }
  61464. if (nV1 && nV2 && nV3 && nV4) {
  61465. result.push(nV1.clone());
  61466. result.push(nV2.clone());
  61467. result.push(nV3);
  61468. result.push(nV4);
  61469. result.push(nV3.clone());
  61470. result.push(nV2.clone());
  61471. }
  61472. break;
  61473. case 2:
  61474. if (!v1Out) {
  61475. nV1 = vertices[index].clone();
  61476. nV2 = clipVertices(nV1, vertices[index + 1]);
  61477. nV3 = clipVertices(nV1, vertices[index + 2]);
  61478. result.push(nV1);
  61479. result.push(nV2);
  61480. result.push(nV3);
  61481. }
  61482. if (!v2Out) {
  61483. nV1 = vertices[index + 1].clone();
  61484. nV2 = clipVertices(nV1, vertices[index + 2]);
  61485. nV3 = clipVertices(nV1, vertices[index]);
  61486. result.push(nV1);
  61487. result.push(nV2);
  61488. result.push(nV3);
  61489. }
  61490. if (!v3Out) {
  61491. nV1 = vertices[index + 2].clone();
  61492. nV2 = clipVertices(nV1, vertices[index]);
  61493. nV3 = clipVertices(nV1, vertices[index + 1]);
  61494. result.push(nV1);
  61495. result.push(nV2);
  61496. result.push(nV3);
  61497. }
  61498. break;
  61499. case 3:
  61500. break;
  61501. }
  61502. }
  61503. return result;
  61504. };
  61505. for (var index = 0; index < indices.length; index += 3) {
  61506. var faceVertices = new Array();
  61507. faceVertices.push(extractDecalVector3(index));
  61508. faceVertices.push(extractDecalVector3(index + 1));
  61509. faceVertices.push(extractDecalVector3(index + 2));
  61510. // Clip
  61511. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61512. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61513. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61514. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61515. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61516. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61517. if (faceVertices.length === 0) {
  61518. continue;
  61519. }
  61520. // Add UVs and get back to world
  61521. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61522. var vertex = faceVertices[vIndex];
  61523. //TODO check for Int32Array | Uint32Array | Uint16Array
  61524. vertexData.indices.push(currentVertexDataIndex);
  61525. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61526. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61527. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61528. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61529. currentVertexDataIndex++;
  61530. }
  61531. }
  61532. // Return mesh
  61533. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61534. vertexData.applyToMesh(decal);
  61535. decal.position = position.clone();
  61536. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61537. return decal;
  61538. };
  61539. // Privates
  61540. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61541. // extrusion geometry
  61542. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61543. var tangents = path3D.getTangents();
  61544. var normals = path3D.getNormals();
  61545. var binormals = path3D.getBinormals();
  61546. var distances = path3D.getDistances();
  61547. var angle = 0;
  61548. var returnScale = function () { return scale !== null ? scale : 1; };
  61549. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61550. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61551. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61552. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61553. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61554. for (var i = 0; i < curve.length; i++) {
  61555. var shapePath = new Array();
  61556. var angleStep = rotate(i, distances[i]);
  61557. var scaleRatio = scl(i, distances[i]);
  61558. for (var p = 0; p < shape.length; p++) {
  61559. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61560. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61561. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61562. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61563. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61564. shapePath[p] = rotated;
  61565. }
  61566. shapePaths[index] = shapePath;
  61567. angle += angleStep;
  61568. index++;
  61569. }
  61570. // cap
  61571. var capPath = function (shapePath) {
  61572. var pointCap = Array();
  61573. var barycenter = BABYLON.Vector3.Zero();
  61574. var i;
  61575. for (i = 0; i < shapePath.length; i++) {
  61576. barycenter.addInPlace(shapePath[i]);
  61577. }
  61578. barycenter.scaleInPlace(1.0 / shapePath.length);
  61579. for (i = 0; i < shapePath.length; i++) {
  61580. pointCap.push(barycenter);
  61581. }
  61582. return pointCap;
  61583. };
  61584. switch (cap) {
  61585. case BABYLON.Mesh.NO_CAP:
  61586. break;
  61587. case BABYLON.Mesh.CAP_START:
  61588. shapePaths[0] = capPath(shapePaths[2]);
  61589. shapePaths[1] = shapePaths[2];
  61590. break;
  61591. case BABYLON.Mesh.CAP_END:
  61592. shapePaths[index] = shapePaths[index - 1];
  61593. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61594. break;
  61595. case BABYLON.Mesh.CAP_ALL:
  61596. shapePaths[0] = capPath(shapePaths[2]);
  61597. shapePaths[1] = shapePaths[2];
  61598. shapePaths[index] = shapePaths[index - 1];
  61599. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61600. break;
  61601. default:
  61602. break;
  61603. }
  61604. return shapePaths;
  61605. };
  61606. var path3D;
  61607. var pathArray;
  61608. if (instance) { // instance update
  61609. path3D = (instance.path3D).update(curve);
  61610. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61611. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61612. return instance;
  61613. }
  61614. // extruded shape creation
  61615. path3D = new BABYLON.Path3D(curve);
  61616. var newShapePaths = new Array();
  61617. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61618. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61619. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61620. extrudedGeneric.pathArray = pathArray;
  61621. extrudedGeneric.path3D = path3D;
  61622. extrudedGeneric.cap = cap;
  61623. return extrudedGeneric;
  61624. };
  61625. return MeshBuilder;
  61626. }());
  61627. BABYLON.MeshBuilder = MeshBuilder;
  61628. })(BABYLON || (BABYLON = {}));
  61629. //# sourceMappingURL=babylon.meshBuilder.js.map
  61630. var BABYLON;
  61631. (function (BABYLON) {
  61632. /**
  61633. * Draco compression (https://google.github.io/draco/)
  61634. */
  61635. var DracoCompression = /** @class */ (function () {
  61636. /**
  61637. * Constructor
  61638. */
  61639. function DracoCompression() {
  61640. }
  61641. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61642. /**
  61643. * Returns true if the decoder is available.
  61644. */
  61645. get: function () {
  61646. if (typeof DracoDecoderModule !== "undefined") {
  61647. return true;
  61648. }
  61649. var decoder = DracoCompression.Configuration.decoder;
  61650. if (decoder) {
  61651. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61652. return true;
  61653. }
  61654. if (decoder.fallbackUrl) {
  61655. return true;
  61656. }
  61657. }
  61658. return false;
  61659. },
  61660. enumerable: true,
  61661. configurable: true
  61662. });
  61663. /**
  61664. * Stop all async operations and release resources.
  61665. */
  61666. DracoCompression.prototype.dispose = function () {
  61667. };
  61668. /**
  61669. * Decode Draco compressed mesh data to vertex data.
  61670. * @param data The array buffer view for the Draco compression data
  61671. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61672. * @returns A promise that resolves with the decoded vertex data
  61673. */
  61674. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61675. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61676. var module = wrappedModule.module;
  61677. var vertexData = new BABYLON.VertexData();
  61678. var buffer = new module.DecoderBuffer();
  61679. buffer.Init(data, data.byteLength);
  61680. var decoder = new module.Decoder();
  61681. var geometry;
  61682. var status;
  61683. try {
  61684. var type = decoder.GetEncodedGeometryType(buffer);
  61685. switch (type) {
  61686. case module.TRIANGULAR_MESH:
  61687. geometry = new module.Mesh();
  61688. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61689. break;
  61690. case module.POINT_CLOUD:
  61691. geometry = new module.PointCloud();
  61692. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61693. break;
  61694. default:
  61695. throw new Error("Invalid geometry type " + type);
  61696. }
  61697. if (!status.ok() || !geometry.ptr) {
  61698. throw new Error(status.error_msg());
  61699. }
  61700. var numPoints = geometry.num_points();
  61701. if (type === module.TRIANGULAR_MESH) {
  61702. var numFaces = geometry.num_faces();
  61703. var faceIndices = new module.DracoInt32Array();
  61704. try {
  61705. var indices = new Uint32Array(numFaces * 3);
  61706. for (var i = 0; i < numFaces; i++) {
  61707. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61708. var offset = i * 3;
  61709. indices[offset + 0] = faceIndices.GetValue(0);
  61710. indices[offset + 1] = faceIndices.GetValue(1);
  61711. indices[offset + 2] = faceIndices.GetValue(2);
  61712. }
  61713. vertexData.indices = indices;
  61714. }
  61715. finally {
  61716. module.destroy(faceIndices);
  61717. }
  61718. }
  61719. for (var kind in attributes) {
  61720. var uniqueId = attributes[kind];
  61721. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61722. var dracoData = new module.DracoFloat32Array();
  61723. try {
  61724. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61725. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61726. for (var i = 0; i < babylonData.length; i++) {
  61727. babylonData[i] = dracoData.GetValue(i);
  61728. }
  61729. vertexData.set(babylonData, kind);
  61730. }
  61731. finally {
  61732. module.destroy(dracoData);
  61733. }
  61734. }
  61735. }
  61736. finally {
  61737. if (geometry) {
  61738. module.destroy(geometry);
  61739. }
  61740. module.destroy(decoder);
  61741. module.destroy(buffer);
  61742. }
  61743. return vertexData;
  61744. });
  61745. };
  61746. DracoCompression._GetDecoderModule = function () {
  61747. if (!DracoCompression._DecoderModulePromise) {
  61748. var promise = null;
  61749. var config_1 = {};
  61750. if (typeof DracoDecoderModule !== "undefined") {
  61751. promise = Promise.resolve();
  61752. }
  61753. else {
  61754. var decoder = DracoCompression.Configuration.decoder;
  61755. if (decoder) {
  61756. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61757. promise = Promise.all([
  61758. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61759. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61760. config_1.wasmBinary = data;
  61761. })
  61762. ]);
  61763. }
  61764. else if (decoder.fallbackUrl) {
  61765. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61766. }
  61767. }
  61768. }
  61769. if (!promise) {
  61770. throw new Error("Draco decoder module is not available");
  61771. }
  61772. DracoCompression._DecoderModulePromise = promise.then(function () {
  61773. return new Promise(function (resolve) {
  61774. config_1.onModuleLoaded = function (decoderModule) {
  61775. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61776. resolve({ module: decoderModule });
  61777. };
  61778. DracoDecoderModule(config_1);
  61779. });
  61780. });
  61781. }
  61782. return DracoCompression._DecoderModulePromise;
  61783. };
  61784. DracoCompression._LoadScriptAsync = function (url) {
  61785. return new Promise(function (resolve, reject) {
  61786. BABYLON.Tools.LoadScript(url, function () {
  61787. resolve();
  61788. }, function (message) {
  61789. reject(new Error(message));
  61790. });
  61791. });
  61792. };
  61793. DracoCompression._LoadFileAsync = function (url) {
  61794. return new Promise(function (resolve, reject) {
  61795. BABYLON.Tools.LoadFile(url, function (data) {
  61796. resolve(data);
  61797. }, undefined, undefined, true, function (request, exception) {
  61798. reject(exception);
  61799. });
  61800. });
  61801. };
  61802. /**
  61803. * The configuration.
  61804. */
  61805. DracoCompression.Configuration = {
  61806. decoder: {
  61807. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61808. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61809. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61810. }
  61811. };
  61812. return DracoCompression;
  61813. }());
  61814. BABYLON.DracoCompression = DracoCompression;
  61815. })(BABYLON || (BABYLON = {}));
  61816. //# sourceMappingURL=babylon.dracoCompression.js.map
  61817. var BABYLON;
  61818. (function (BABYLON) {
  61819. var AudioEngine = /** @class */ (function () {
  61820. function AudioEngine() {
  61821. this._audioContext = null;
  61822. this._audioContextInitialized = false;
  61823. this.canUseWebAudio = false;
  61824. this.WarnedWebAudioUnsupported = false;
  61825. this.unlocked = false;
  61826. this.isMP3supported = false;
  61827. this.isOGGsupported = false;
  61828. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61829. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61830. this.canUseWebAudio = true;
  61831. }
  61832. var audioElem = document.createElement('audio');
  61833. try {
  61834. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61835. this.isMP3supported = true;
  61836. }
  61837. }
  61838. catch (e) {
  61839. // protect error during capability check.
  61840. }
  61841. try {
  61842. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61843. this.isOGGsupported = true;
  61844. }
  61845. }
  61846. catch (e) {
  61847. // protect error during capability check.
  61848. }
  61849. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61850. this._unlockiOSaudio();
  61851. }
  61852. else {
  61853. this.unlocked = true;
  61854. }
  61855. }
  61856. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61857. get: function () {
  61858. if (!this._audioContextInitialized) {
  61859. this._initializeAudioContext();
  61860. }
  61861. return this._audioContext;
  61862. },
  61863. enumerable: true,
  61864. configurable: true
  61865. });
  61866. AudioEngine.prototype._unlockiOSaudio = function () {
  61867. var _this = this;
  61868. var unlockaudio = function () {
  61869. if (!_this.audioContext) {
  61870. return;
  61871. }
  61872. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61873. var source = _this.audioContext.createBufferSource();
  61874. source.buffer = buffer;
  61875. source.connect(_this.audioContext.destination);
  61876. source.start(0);
  61877. setTimeout(function () {
  61878. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61879. _this.unlocked = true;
  61880. window.removeEventListener('touchend', unlockaudio, false);
  61881. if (_this.onAudioUnlocked) {
  61882. _this.onAudioUnlocked();
  61883. }
  61884. }
  61885. }, 0);
  61886. };
  61887. window.addEventListener('touchend', unlockaudio, false);
  61888. };
  61889. AudioEngine.prototype._initializeAudioContext = function () {
  61890. try {
  61891. if (this.canUseWebAudio) {
  61892. this._audioContext = new AudioContext();
  61893. // create a global volume gain node
  61894. this.masterGain = this._audioContext.createGain();
  61895. this.masterGain.gain.value = 1;
  61896. this.masterGain.connect(this._audioContext.destination);
  61897. this._audioContextInitialized = true;
  61898. }
  61899. }
  61900. catch (e) {
  61901. this.canUseWebAudio = false;
  61902. BABYLON.Tools.Error("Web Audio: " + e.message);
  61903. }
  61904. };
  61905. AudioEngine.prototype.dispose = function () {
  61906. if (this.canUseWebAudio && this._audioContextInitialized) {
  61907. if (this._connectedAnalyser && this._audioContext) {
  61908. this._connectedAnalyser.stopDebugCanvas();
  61909. this._connectedAnalyser.dispose();
  61910. this.masterGain.disconnect();
  61911. this.masterGain.connect(this._audioContext.destination);
  61912. this._connectedAnalyser = null;
  61913. }
  61914. this.masterGain.gain.value = 1;
  61915. }
  61916. this.WarnedWebAudioUnsupported = false;
  61917. };
  61918. AudioEngine.prototype.getGlobalVolume = function () {
  61919. if (this.canUseWebAudio && this._audioContextInitialized) {
  61920. return this.masterGain.gain.value;
  61921. }
  61922. else {
  61923. return -1;
  61924. }
  61925. };
  61926. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61927. if (this.canUseWebAudio && this._audioContextInitialized) {
  61928. this.masterGain.gain.value = newVolume;
  61929. }
  61930. };
  61931. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61932. if (this._connectedAnalyser) {
  61933. this._connectedAnalyser.stopDebugCanvas();
  61934. }
  61935. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61936. this._connectedAnalyser = analyser;
  61937. this.masterGain.disconnect();
  61938. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61939. }
  61940. };
  61941. return AudioEngine;
  61942. }());
  61943. BABYLON.AudioEngine = AudioEngine;
  61944. })(BABYLON || (BABYLON = {}));
  61945. //# sourceMappingURL=babylon.audioEngine.js.map
  61946. var BABYLON;
  61947. (function (BABYLON) {
  61948. var Sound = /** @class */ (function () {
  61949. /**
  61950. * Create a sound and attach it to a scene
  61951. * @param name Name of your sound
  61952. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61953. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61954. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61955. */
  61956. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61957. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61958. var _this = this;
  61959. this.autoplay = false;
  61960. this.loop = false;
  61961. this.useCustomAttenuation = false;
  61962. this.spatialSound = false;
  61963. this.refDistance = 1;
  61964. this.rolloffFactor = 1;
  61965. this.maxDistance = 100;
  61966. this.distanceModel = "linear";
  61967. this._panningModel = "equalpower";
  61968. this._playbackRate = 1;
  61969. this._streaming = false;
  61970. this._startTime = 0;
  61971. this._startOffset = 0;
  61972. this._position = BABYLON.Vector3.Zero();
  61973. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61974. this._volume = 1;
  61975. this._isReadyToPlay = false;
  61976. this.isPlaying = false;
  61977. this.isPaused = false;
  61978. this._isDirectional = false;
  61979. // Used if you'd like to create a directional sound.
  61980. // If not set, the sound will be omnidirectional
  61981. this._coneInnerAngle = 360;
  61982. this._coneOuterAngle = 360;
  61983. this._coneOuterGain = 0;
  61984. this._isOutputConnected = false;
  61985. this._urlType = "Unknown";
  61986. this.name = name;
  61987. this._scene = scene;
  61988. this._readyToPlayCallback = readyToPlayCallback;
  61989. // Default custom attenuation function is a linear attenuation
  61990. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61991. if (currentDistance < maxDistance) {
  61992. return currentVolume * (1 - currentDistance / maxDistance);
  61993. }
  61994. else {
  61995. return 0;
  61996. }
  61997. };
  61998. if (options) {
  61999. this.autoplay = options.autoplay || false;
  62000. this.loop = options.loop || false;
  62001. // if volume === 0, we need another way to check this option
  62002. if (options.volume !== undefined) {
  62003. this._volume = options.volume;
  62004. }
  62005. this.spatialSound = options.spatialSound || false;
  62006. this.maxDistance = options.maxDistance || 100;
  62007. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62008. this.rolloffFactor = options.rolloffFactor || 1;
  62009. this.refDistance = options.refDistance || 1;
  62010. this.distanceModel = options.distanceModel || "linear";
  62011. this._playbackRate = options.playbackRate || 1;
  62012. this._streaming = options.streaming || false;
  62013. }
  62014. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62015. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62016. this._soundGain.gain.value = this._volume;
  62017. this._inputAudioNode = this._soundGain;
  62018. this._ouputAudioNode = this._soundGain;
  62019. if (this.spatialSound) {
  62020. this._createSpatialParameters();
  62021. }
  62022. this._scene.mainSoundTrack.AddSound(this);
  62023. var validParameter = true;
  62024. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62025. if (urlOrArrayBuffer) {
  62026. try {
  62027. if (typeof (urlOrArrayBuffer) === "string")
  62028. this._urlType = "String";
  62029. if (Array.isArray(urlOrArrayBuffer))
  62030. this._urlType = "Array";
  62031. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62032. this._urlType = "ArrayBuffer";
  62033. var urls = [];
  62034. var codecSupportedFound = false;
  62035. switch (this._urlType) {
  62036. case "ArrayBuffer":
  62037. if (urlOrArrayBuffer.byteLength > 0) {
  62038. codecSupportedFound = true;
  62039. this._soundLoaded(urlOrArrayBuffer);
  62040. }
  62041. break;
  62042. case "String":
  62043. urls.push(urlOrArrayBuffer);
  62044. case "Array":
  62045. if (urls.length === 0)
  62046. urls = urlOrArrayBuffer;
  62047. // If we found a supported format, we load it immediately and stop the loop
  62048. for (var i = 0; i < urls.length; i++) {
  62049. var url = urls[i];
  62050. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62051. codecSupportedFound = true;
  62052. }
  62053. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62054. codecSupportedFound = true;
  62055. }
  62056. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62057. codecSupportedFound = true;
  62058. }
  62059. if (url.indexOf("blob:") !== -1) {
  62060. codecSupportedFound = true;
  62061. }
  62062. if (codecSupportedFound) {
  62063. // Loading sound using XHR2
  62064. if (!this._streaming) {
  62065. this._scene._loadFile(url, function (data) {
  62066. _this._soundLoaded(data);
  62067. }, undefined, true, true, function (exception) {
  62068. if (exception) {
  62069. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62070. }
  62071. BABYLON.Tools.Error("Sound creation aborted.");
  62072. _this._scene.mainSoundTrack.RemoveSound(_this);
  62073. });
  62074. }
  62075. // Streaming sound using HTML5 Audio tag
  62076. else {
  62077. this._htmlAudioElement = new Audio(url);
  62078. this._htmlAudioElement.controls = false;
  62079. this._htmlAudioElement.loop = this.loop;
  62080. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62081. this._htmlAudioElement.preload = "auto";
  62082. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62083. _this._isReadyToPlay = true;
  62084. if (_this.autoplay) {
  62085. _this.play();
  62086. }
  62087. if (_this._readyToPlayCallback) {
  62088. _this._readyToPlayCallback();
  62089. }
  62090. });
  62091. document.body.appendChild(this._htmlAudioElement);
  62092. }
  62093. break;
  62094. }
  62095. }
  62096. break;
  62097. default:
  62098. validParameter = false;
  62099. break;
  62100. }
  62101. if (!validParameter) {
  62102. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62103. }
  62104. else {
  62105. if (!codecSupportedFound) {
  62106. this._isReadyToPlay = true;
  62107. // Simulating a ready to play event to avoid breaking code path
  62108. if (this._readyToPlayCallback) {
  62109. window.setTimeout(function () {
  62110. if (_this._readyToPlayCallback) {
  62111. _this._readyToPlayCallback();
  62112. }
  62113. }, 1000);
  62114. }
  62115. }
  62116. }
  62117. }
  62118. catch (ex) {
  62119. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62120. this._scene.mainSoundTrack.RemoveSound(this);
  62121. }
  62122. }
  62123. }
  62124. else {
  62125. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62126. this._scene.mainSoundTrack.AddSound(this);
  62127. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62128. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62129. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62130. }
  62131. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62132. if (this._readyToPlayCallback) {
  62133. window.setTimeout(function () {
  62134. if (_this._readyToPlayCallback) {
  62135. _this._readyToPlayCallback();
  62136. }
  62137. }, 1000);
  62138. }
  62139. }
  62140. }
  62141. Sound.prototype.dispose = function () {
  62142. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62143. if (this.isPlaying) {
  62144. this.stop();
  62145. }
  62146. this._isReadyToPlay = false;
  62147. if (this.soundTrackId === -1) {
  62148. this._scene.mainSoundTrack.RemoveSound(this);
  62149. }
  62150. else {
  62151. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62152. }
  62153. if (this._soundGain) {
  62154. this._soundGain.disconnect();
  62155. this._soundGain = null;
  62156. }
  62157. if (this._soundPanner) {
  62158. this._soundPanner.disconnect();
  62159. this._soundPanner = null;
  62160. }
  62161. if (this._soundSource) {
  62162. this._soundSource.disconnect();
  62163. this._soundSource = null;
  62164. }
  62165. this._audioBuffer = null;
  62166. if (this._htmlAudioElement) {
  62167. this._htmlAudioElement.pause();
  62168. this._htmlAudioElement.src = "";
  62169. document.body.removeChild(this._htmlAudioElement);
  62170. }
  62171. if (this._connectedMesh && this._registerFunc) {
  62172. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62173. this._connectedMesh = null;
  62174. }
  62175. }
  62176. };
  62177. Sound.prototype.isReady = function () {
  62178. return this._isReadyToPlay;
  62179. };
  62180. Sound.prototype._soundLoaded = function (audioData) {
  62181. var _this = this;
  62182. if (!BABYLON.Engine.audioEngine.audioContext) {
  62183. return;
  62184. }
  62185. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62186. _this._audioBuffer = buffer;
  62187. _this._isReadyToPlay = true;
  62188. if (_this.autoplay) {
  62189. _this.play();
  62190. }
  62191. if (_this._readyToPlayCallback) {
  62192. _this._readyToPlayCallback();
  62193. }
  62194. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62195. };
  62196. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62197. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62198. this._audioBuffer = audioBuffer;
  62199. this._isReadyToPlay = true;
  62200. }
  62201. };
  62202. Sound.prototype.updateOptions = function (options) {
  62203. if (options) {
  62204. this.loop = options.loop || this.loop;
  62205. this.maxDistance = options.maxDistance || this.maxDistance;
  62206. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62207. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62208. this.refDistance = options.refDistance || this.refDistance;
  62209. this.distanceModel = options.distanceModel || this.distanceModel;
  62210. this._playbackRate = options.playbackRate || this._playbackRate;
  62211. this._updateSpatialParameters();
  62212. if (this.isPlaying) {
  62213. if (this._streaming) {
  62214. this._htmlAudioElement.playbackRate = this._playbackRate;
  62215. }
  62216. else {
  62217. if (this._soundSource) {
  62218. this._soundSource.playbackRate.value = this._playbackRate;
  62219. }
  62220. }
  62221. }
  62222. }
  62223. };
  62224. Sound.prototype._createSpatialParameters = function () {
  62225. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62226. if (this._scene.headphone) {
  62227. this._panningModel = "HRTF";
  62228. }
  62229. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62230. this._updateSpatialParameters();
  62231. this._soundPanner.connect(this._ouputAudioNode);
  62232. this._inputAudioNode = this._soundPanner;
  62233. }
  62234. };
  62235. Sound.prototype._updateSpatialParameters = function () {
  62236. if (this.spatialSound && this._soundPanner) {
  62237. if (this.useCustomAttenuation) {
  62238. // Tricks to disable in a way embedded Web Audio attenuation
  62239. this._soundPanner.distanceModel = "linear";
  62240. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62241. this._soundPanner.refDistance = 1;
  62242. this._soundPanner.rolloffFactor = 1;
  62243. this._soundPanner.panningModel = this._panningModel;
  62244. }
  62245. else {
  62246. this._soundPanner.distanceModel = this.distanceModel;
  62247. this._soundPanner.maxDistance = this.maxDistance;
  62248. this._soundPanner.refDistance = this.refDistance;
  62249. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62250. this._soundPanner.panningModel = this._panningModel;
  62251. }
  62252. }
  62253. };
  62254. Sound.prototype.switchPanningModelToHRTF = function () {
  62255. this._panningModel = "HRTF";
  62256. this._switchPanningModel();
  62257. };
  62258. Sound.prototype.switchPanningModelToEqualPower = function () {
  62259. this._panningModel = "equalpower";
  62260. this._switchPanningModel();
  62261. };
  62262. Sound.prototype._switchPanningModel = function () {
  62263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62264. this._soundPanner.panningModel = this._panningModel;
  62265. }
  62266. };
  62267. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62268. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62269. if (this._isOutputConnected) {
  62270. this._ouputAudioNode.disconnect();
  62271. }
  62272. this._ouputAudioNode.connect(soundTrackAudioNode);
  62273. this._isOutputConnected = true;
  62274. }
  62275. };
  62276. /**
  62277. * Transform this sound into a directional source
  62278. * @param coneInnerAngle Size of the inner cone in degree
  62279. * @param coneOuterAngle Size of the outer cone in degree
  62280. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62281. */
  62282. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62283. if (coneOuterAngle < coneInnerAngle) {
  62284. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62285. return;
  62286. }
  62287. this._coneInnerAngle = coneInnerAngle;
  62288. this._coneOuterAngle = coneOuterAngle;
  62289. this._coneOuterGain = coneOuterGain;
  62290. this._isDirectional = true;
  62291. if (this.isPlaying && this.loop) {
  62292. this.stop();
  62293. this.play();
  62294. }
  62295. };
  62296. Sound.prototype.setPosition = function (newPosition) {
  62297. this._position = newPosition;
  62298. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62299. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62300. }
  62301. };
  62302. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62303. this._localDirection = newLocalDirection;
  62304. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62305. this._updateDirection();
  62306. }
  62307. };
  62308. Sound.prototype._updateDirection = function () {
  62309. if (!this._connectedMesh || !this._soundPanner) {
  62310. return;
  62311. }
  62312. var mat = this._connectedMesh.getWorldMatrix();
  62313. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62314. direction.normalize();
  62315. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62316. };
  62317. Sound.prototype.updateDistanceFromListener = function () {
  62318. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62319. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62320. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62321. }
  62322. };
  62323. Sound.prototype.setAttenuationFunction = function (callback) {
  62324. this._customAttenuationFunction = callback;
  62325. };
  62326. /**
  62327. * Play the sound
  62328. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62329. * @param offset (optional) Start the sound setting it at a specific time
  62330. */
  62331. Sound.prototype.play = function (time, offset) {
  62332. var _this = this;
  62333. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62334. try {
  62335. if (this._startOffset < 0) {
  62336. time = -this._startOffset;
  62337. this._startOffset = 0;
  62338. }
  62339. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62340. if (!this._soundSource || !this._streamingSource) {
  62341. if (this.spatialSound && this._soundPanner) {
  62342. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62343. if (this._isDirectional) {
  62344. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62345. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62346. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62347. if (this._connectedMesh) {
  62348. this._updateDirection();
  62349. }
  62350. else {
  62351. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62352. }
  62353. }
  62354. }
  62355. }
  62356. if (this._streaming) {
  62357. if (!this._streamingSource) {
  62358. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62359. this._htmlAudioElement.onended = function () { _this._onended(); };
  62360. this._htmlAudioElement.playbackRate = this._playbackRate;
  62361. }
  62362. this._streamingSource.disconnect();
  62363. this._streamingSource.connect(this._inputAudioNode);
  62364. this._htmlAudioElement.play();
  62365. }
  62366. else {
  62367. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62368. this._soundSource.buffer = this._audioBuffer;
  62369. this._soundSource.connect(this._inputAudioNode);
  62370. this._soundSource.loop = this.loop;
  62371. this._soundSource.playbackRate.value = this._playbackRate;
  62372. this._soundSource.onended = function () { _this._onended(); };
  62373. if (this._soundSource.buffer) {
  62374. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62375. }
  62376. }
  62377. this._startTime = startTime;
  62378. this.isPlaying = true;
  62379. this.isPaused = false;
  62380. }
  62381. catch (ex) {
  62382. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62383. }
  62384. }
  62385. };
  62386. Sound.prototype._onended = function () {
  62387. this.isPlaying = false;
  62388. if (this.onended) {
  62389. this.onended();
  62390. }
  62391. };
  62392. /**
  62393. * Stop the sound
  62394. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62395. */
  62396. Sound.prototype.stop = function (time) {
  62397. if (this.isPlaying) {
  62398. if (this._streaming) {
  62399. this._htmlAudioElement.pause();
  62400. // Test needed for Firefox or it will generate an Invalid State Error
  62401. if (this._htmlAudioElement.currentTime > 0) {
  62402. this._htmlAudioElement.currentTime = 0;
  62403. }
  62404. }
  62405. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62406. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62407. this._soundSource.stop(stopTime);
  62408. this._soundSource.onended = function () { };
  62409. if (!this.isPaused) {
  62410. this._startOffset = 0;
  62411. }
  62412. }
  62413. this.isPlaying = false;
  62414. }
  62415. };
  62416. Sound.prototype.pause = function () {
  62417. if (this.isPlaying) {
  62418. this.isPaused = true;
  62419. if (this._streaming) {
  62420. this._htmlAudioElement.pause();
  62421. }
  62422. else if (BABYLON.Engine.audioEngine.audioContext) {
  62423. this.stop(0);
  62424. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62425. }
  62426. }
  62427. };
  62428. Sound.prototype.setVolume = function (newVolume, time) {
  62429. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62430. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62431. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62432. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62433. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62434. }
  62435. else {
  62436. this._soundGain.gain.value = newVolume;
  62437. }
  62438. }
  62439. this._volume = newVolume;
  62440. };
  62441. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62442. this._playbackRate = newPlaybackRate;
  62443. if (this.isPlaying) {
  62444. if (this._streaming) {
  62445. this._htmlAudioElement.playbackRate = this._playbackRate;
  62446. }
  62447. else if (this._soundSource) {
  62448. this._soundSource.playbackRate.value = this._playbackRate;
  62449. }
  62450. }
  62451. };
  62452. Sound.prototype.getVolume = function () {
  62453. return this._volume;
  62454. };
  62455. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62456. var _this = this;
  62457. if (this._connectedMesh && this._registerFunc) {
  62458. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62459. this._registerFunc = null;
  62460. }
  62461. this._connectedMesh = meshToConnectTo;
  62462. if (!this.spatialSound) {
  62463. this.spatialSound = true;
  62464. this._createSpatialParameters();
  62465. if (this.isPlaying && this.loop) {
  62466. this.stop();
  62467. this.play();
  62468. }
  62469. }
  62470. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62471. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62472. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62473. };
  62474. Sound.prototype.detachFromMesh = function () {
  62475. if (this._connectedMesh && this._registerFunc) {
  62476. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62477. this._registerFunc = null;
  62478. this._connectedMesh = null;
  62479. }
  62480. };
  62481. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62482. if (!node.getBoundingInfo) {
  62483. return;
  62484. }
  62485. var mesh = node;
  62486. var boundingInfo = mesh.getBoundingInfo();
  62487. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62488. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62489. this._updateDirection();
  62490. }
  62491. };
  62492. Sound.prototype.clone = function () {
  62493. var _this = this;
  62494. if (!this._streaming) {
  62495. var setBufferAndRun = function () {
  62496. if (_this._isReadyToPlay) {
  62497. clonedSound._audioBuffer = _this.getAudioBuffer();
  62498. clonedSound._isReadyToPlay = true;
  62499. if (clonedSound.autoplay) {
  62500. clonedSound.play();
  62501. }
  62502. }
  62503. else {
  62504. window.setTimeout(setBufferAndRun, 300);
  62505. }
  62506. };
  62507. var currentOptions = {
  62508. autoplay: this.autoplay, loop: this.loop,
  62509. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62510. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62511. refDistance: this.refDistance, distanceModel: this.distanceModel
  62512. };
  62513. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62514. if (this.useCustomAttenuation) {
  62515. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62516. }
  62517. clonedSound.setPosition(this._position);
  62518. clonedSound.setPlaybackRate(this._playbackRate);
  62519. setBufferAndRun();
  62520. return clonedSound;
  62521. }
  62522. // Can't clone a streaming sound
  62523. else {
  62524. return null;
  62525. }
  62526. };
  62527. Sound.prototype.getAudioBuffer = function () {
  62528. return this._audioBuffer;
  62529. };
  62530. Sound.prototype.serialize = function () {
  62531. var serializationObject = {
  62532. name: this.name,
  62533. url: this.name,
  62534. autoplay: this.autoplay,
  62535. loop: this.loop,
  62536. volume: this._volume,
  62537. spatialSound: this.spatialSound,
  62538. maxDistance: this.maxDistance,
  62539. rolloffFactor: this.rolloffFactor,
  62540. refDistance: this.refDistance,
  62541. distanceModel: this.distanceModel,
  62542. playbackRate: this._playbackRate,
  62543. panningModel: this._panningModel,
  62544. soundTrackId: this.soundTrackId
  62545. };
  62546. if (this.spatialSound) {
  62547. if (this._connectedMesh)
  62548. serializationObject.connectedMeshId = this._connectedMesh.id;
  62549. serializationObject.position = this._position.asArray();
  62550. serializationObject.refDistance = this.refDistance;
  62551. serializationObject.distanceModel = this.distanceModel;
  62552. serializationObject.isDirectional = this._isDirectional;
  62553. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62554. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62555. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62556. serializationObject.coneOuterGain = this._coneOuterGain;
  62557. }
  62558. return serializationObject;
  62559. };
  62560. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62561. var soundName = parsedSound.name;
  62562. var soundUrl;
  62563. if (parsedSound.url) {
  62564. soundUrl = rootUrl + parsedSound.url;
  62565. }
  62566. else {
  62567. soundUrl = rootUrl + soundName;
  62568. }
  62569. var options = {
  62570. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62571. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62572. rolloffFactor: parsedSound.rolloffFactor,
  62573. refDistance: parsedSound.refDistance,
  62574. distanceModel: parsedSound.distanceModel,
  62575. playbackRate: parsedSound.playbackRate
  62576. };
  62577. var newSound;
  62578. if (!sourceSound) {
  62579. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62580. scene._addPendingData(newSound);
  62581. }
  62582. else {
  62583. var setBufferAndRun = function () {
  62584. if (sourceSound._isReadyToPlay) {
  62585. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62586. newSound._isReadyToPlay = true;
  62587. if (newSound.autoplay) {
  62588. newSound.play();
  62589. }
  62590. }
  62591. else {
  62592. window.setTimeout(setBufferAndRun, 300);
  62593. }
  62594. };
  62595. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62596. setBufferAndRun();
  62597. }
  62598. if (parsedSound.position) {
  62599. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62600. newSound.setPosition(soundPosition);
  62601. }
  62602. if (parsedSound.isDirectional) {
  62603. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62604. if (parsedSound.localDirectionToMesh) {
  62605. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62606. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62607. }
  62608. }
  62609. if (parsedSound.connectedMeshId) {
  62610. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62611. if (connectedMesh) {
  62612. newSound.attachToMesh(connectedMesh);
  62613. }
  62614. }
  62615. return newSound;
  62616. };
  62617. return Sound;
  62618. }());
  62619. BABYLON.Sound = Sound;
  62620. })(BABYLON || (BABYLON = {}));
  62621. //# sourceMappingURL=babylon.sound.js.map
  62622. var BABYLON;
  62623. (function (BABYLON) {
  62624. var SoundTrack = /** @class */ (function () {
  62625. function SoundTrack(scene, options) {
  62626. this.id = -1;
  62627. this._isMainTrack = false;
  62628. this._isInitialized = false;
  62629. this._scene = scene;
  62630. this.soundCollection = new Array();
  62631. this._options = options;
  62632. if (!this._isMainTrack) {
  62633. this._scene.soundTracks.push(this);
  62634. this.id = this._scene.soundTracks.length - 1;
  62635. }
  62636. }
  62637. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62638. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62639. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62640. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62641. if (this._options) {
  62642. if (this._options.volume) {
  62643. this._outputAudioNode.gain.value = this._options.volume;
  62644. }
  62645. if (this._options.mainTrack) {
  62646. this._isMainTrack = this._options.mainTrack;
  62647. }
  62648. }
  62649. this._isInitialized = true;
  62650. }
  62651. };
  62652. SoundTrack.prototype.dispose = function () {
  62653. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62654. if (this._connectedAnalyser) {
  62655. this._connectedAnalyser.stopDebugCanvas();
  62656. }
  62657. while (this.soundCollection.length) {
  62658. this.soundCollection[0].dispose();
  62659. }
  62660. if (this._outputAudioNode) {
  62661. this._outputAudioNode.disconnect();
  62662. }
  62663. this._outputAudioNode = null;
  62664. }
  62665. };
  62666. SoundTrack.prototype.AddSound = function (sound) {
  62667. if (!this._isInitialized) {
  62668. this._initializeSoundTrackAudioGraph();
  62669. }
  62670. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62671. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62672. }
  62673. if (sound.soundTrackId) {
  62674. if (sound.soundTrackId === -1) {
  62675. this._scene.mainSoundTrack.RemoveSound(sound);
  62676. }
  62677. else {
  62678. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62679. }
  62680. }
  62681. this.soundCollection.push(sound);
  62682. sound.soundTrackId = this.id;
  62683. };
  62684. SoundTrack.prototype.RemoveSound = function (sound) {
  62685. var index = this.soundCollection.indexOf(sound);
  62686. if (index !== -1) {
  62687. this.soundCollection.splice(index, 1);
  62688. }
  62689. };
  62690. SoundTrack.prototype.setVolume = function (newVolume) {
  62691. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62692. this._outputAudioNode.gain.value = newVolume;
  62693. }
  62694. };
  62695. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62696. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62697. for (var i = 0; i < this.soundCollection.length; i++) {
  62698. this.soundCollection[i].switchPanningModelToHRTF();
  62699. }
  62700. }
  62701. };
  62702. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62703. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62704. for (var i = 0; i < this.soundCollection.length; i++) {
  62705. this.soundCollection[i].switchPanningModelToEqualPower();
  62706. }
  62707. }
  62708. };
  62709. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62710. if (this._connectedAnalyser) {
  62711. this._connectedAnalyser.stopDebugCanvas();
  62712. }
  62713. this._connectedAnalyser = analyser;
  62714. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62715. this._outputAudioNode.disconnect();
  62716. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62717. }
  62718. };
  62719. return SoundTrack;
  62720. }());
  62721. BABYLON.SoundTrack = SoundTrack;
  62722. })(BABYLON || (BABYLON = {}));
  62723. //# sourceMappingURL=babylon.soundtrack.js.map
  62724. var BABYLON;
  62725. (function (BABYLON) {
  62726. /**
  62727. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62728. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62729. */
  62730. var Analyser = /** @class */ (function () {
  62731. /**
  62732. * Creates a new analyser
  62733. * @param scene defines hosting scene
  62734. */
  62735. function Analyser(scene) {
  62736. /**
  62737. * Gets or sets the smoothing
  62738. * @ignorenaming
  62739. */
  62740. this.SMOOTHING = 0.75;
  62741. /**
  62742. * Gets or sets the FFT table size
  62743. * @ignorenaming
  62744. */
  62745. this.FFT_SIZE = 512;
  62746. /**
  62747. * Gets or sets the bar graph amplitude
  62748. * @ignorenaming
  62749. */
  62750. this.BARGRAPHAMPLITUDE = 256;
  62751. /**
  62752. * Gets or sets the position of the debug canvas
  62753. * @ignorenaming
  62754. */
  62755. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62756. /**
  62757. * Gets or sets the debug canvas size
  62758. * @ignorenaming
  62759. */
  62760. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62761. this._scene = scene;
  62762. this._audioEngine = BABYLON.Engine.audioEngine;
  62763. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62764. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62765. this._webAudioAnalyser.minDecibels = -140;
  62766. this._webAudioAnalyser.maxDecibels = 0;
  62767. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62768. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62769. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62770. }
  62771. }
  62772. /**
  62773. * Get the number of data values you will have to play with for the visualization
  62774. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62775. * @returns a number
  62776. */
  62777. Analyser.prototype.getFrequencyBinCount = function () {
  62778. if (this._audioEngine.canUseWebAudio) {
  62779. return this._webAudioAnalyser.frequencyBinCount;
  62780. }
  62781. else {
  62782. return 0;
  62783. }
  62784. };
  62785. /**
  62786. * Gets the current frequency data as a byte array
  62787. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62788. * @returns a Uint8Array
  62789. */
  62790. Analyser.prototype.getByteFrequencyData = function () {
  62791. if (this._audioEngine.canUseWebAudio) {
  62792. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62793. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62794. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62795. }
  62796. return this._byteFreqs;
  62797. };
  62798. /**
  62799. * Gets the current waveform as a byte array
  62800. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62801. * @returns a Uint8Array
  62802. */
  62803. Analyser.prototype.getByteTimeDomainData = function () {
  62804. if (this._audioEngine.canUseWebAudio) {
  62805. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62806. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62807. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62808. }
  62809. return this._byteTime;
  62810. };
  62811. /**
  62812. * Gets the current frequency data as a float array
  62813. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62814. * @returns a Float32Array
  62815. */
  62816. Analyser.prototype.getFloatFrequencyData = function () {
  62817. if (this._audioEngine.canUseWebAudio) {
  62818. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62819. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62820. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62821. }
  62822. return this._floatFreqs;
  62823. };
  62824. /**
  62825. * Renders the debug canvas
  62826. */
  62827. Analyser.prototype.drawDebugCanvas = function () {
  62828. var _this = this;
  62829. if (this._audioEngine.canUseWebAudio) {
  62830. if (!this._debugCanvas) {
  62831. this._debugCanvas = document.createElement("canvas");
  62832. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62833. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62834. this._debugCanvas.style.position = "absolute";
  62835. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62836. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62837. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62838. document.body.appendChild(this._debugCanvas);
  62839. this._registerFunc = function () {
  62840. _this.drawDebugCanvas();
  62841. };
  62842. this._scene.registerBeforeRender(this._registerFunc);
  62843. }
  62844. if (this._registerFunc && this._debugCanvasContext) {
  62845. var workingArray = this.getByteFrequencyData();
  62846. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62847. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62848. // Draw the frequency domain chart.
  62849. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62850. var value = workingArray[i];
  62851. var percent = value / this.BARGRAPHAMPLITUDE;
  62852. var height = this.DEBUGCANVASSIZE.height * percent;
  62853. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62854. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62855. var hue = i / this.getFrequencyBinCount() * 360;
  62856. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62857. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62858. }
  62859. }
  62860. }
  62861. };
  62862. /**
  62863. * Stops rendering the debug canvas and removes it
  62864. */
  62865. Analyser.prototype.stopDebugCanvas = function () {
  62866. if (this._debugCanvas) {
  62867. if (this._registerFunc) {
  62868. this._scene.unregisterBeforeRender(this._registerFunc);
  62869. this._registerFunc = null;
  62870. }
  62871. document.body.removeChild(this._debugCanvas);
  62872. this._debugCanvas = null;
  62873. this._debugCanvasContext = null;
  62874. }
  62875. };
  62876. /**
  62877. * Connects two audio nodes
  62878. * @param inputAudioNode defines first node to connect
  62879. * @param outputAudioNode defines second node to connect
  62880. */
  62881. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62882. if (this._audioEngine.canUseWebAudio) {
  62883. inputAudioNode.connect(this._webAudioAnalyser);
  62884. this._webAudioAnalyser.connect(outputAudioNode);
  62885. }
  62886. };
  62887. /**
  62888. * Releases all associated resources
  62889. */
  62890. Analyser.prototype.dispose = function () {
  62891. if (this._audioEngine.canUseWebAudio) {
  62892. this._webAudioAnalyser.disconnect();
  62893. }
  62894. };
  62895. return Analyser;
  62896. }());
  62897. BABYLON.Analyser = Analyser;
  62898. })(BABYLON || (BABYLON = {}));
  62899. //# sourceMappingURL=babylon.analyser.js.map
  62900. var BABYLON;
  62901. (function (BABYLON) {
  62902. var CubeTexture = /** @class */ (function (_super) {
  62903. __extends(CubeTexture, _super);
  62904. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62905. if (extensions === void 0) { extensions = null; }
  62906. if (noMipmap === void 0) { noMipmap = false; }
  62907. if (files === void 0) { files = null; }
  62908. if (onLoad === void 0) { onLoad = null; }
  62909. if (onError === void 0) { onError = null; }
  62910. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62911. if (prefiltered === void 0) { prefiltered = false; }
  62912. if (forcedExtension === void 0) { forcedExtension = null; }
  62913. var _this = _super.call(this, scene) || this;
  62914. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62915. /**
  62916. * Gets or sets the center of the bounding box associated with the cube texture
  62917. * It must define where the camera used to render the texture was set
  62918. */
  62919. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62920. _this._rotationY = 0;
  62921. _this.name = rootUrl;
  62922. _this.url = rootUrl;
  62923. _this._noMipmap = noMipmap;
  62924. _this.hasAlpha = false;
  62925. _this._format = format;
  62926. _this._prefiltered = prefiltered;
  62927. _this.isCube = true;
  62928. _this._textureMatrix = BABYLON.Matrix.Identity();
  62929. if (prefiltered) {
  62930. _this.gammaSpace = false;
  62931. }
  62932. if (!rootUrl && !files) {
  62933. return _this;
  62934. }
  62935. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62936. var lastDot = rootUrl.lastIndexOf(".");
  62937. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62938. var isDDS = (extension === ".dds");
  62939. if (!files) {
  62940. if (!isDDS && !extensions) {
  62941. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62942. }
  62943. files = [];
  62944. if (extensions) {
  62945. for (var index = 0; index < extensions.length; index++) {
  62946. files.push(rootUrl + extensions[index]);
  62947. }
  62948. }
  62949. }
  62950. _this._files = files;
  62951. if (!_this._texture) {
  62952. if (!scene.useDelayedTextureLoading) {
  62953. if (prefiltered) {
  62954. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62955. }
  62956. else {
  62957. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62958. }
  62959. }
  62960. else {
  62961. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62962. }
  62963. }
  62964. else if (onLoad) {
  62965. if (_this._texture.isReady) {
  62966. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62967. }
  62968. else {
  62969. _this._texture.onLoadedObservable.add(onLoad);
  62970. }
  62971. }
  62972. return _this;
  62973. }
  62974. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62975. get: function () {
  62976. return this._boundingBoxSize;
  62977. },
  62978. /**
  62979. * Gets or sets the size of the bounding box associated with the cube texture
  62980. * When defined, the cubemap will switch to local mode
  62981. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62982. * @example https://www.babylonjs-playground.com/#RNASML
  62983. */
  62984. set: function (value) {
  62985. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62986. return;
  62987. }
  62988. this._boundingBoxSize = value;
  62989. var scene = this.getScene();
  62990. if (scene) {
  62991. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62992. }
  62993. },
  62994. enumerable: true,
  62995. configurable: true
  62996. });
  62997. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62998. /**
  62999. * Gets texture matrix rotation angle around Y axis radians.
  63000. */
  63001. get: function () {
  63002. return this._rotationY;
  63003. },
  63004. /**
  63005. * Sets texture matrix rotation angle around Y axis in radians.
  63006. */
  63007. set: function (value) {
  63008. this._rotationY = value;
  63009. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63010. },
  63011. enumerable: true,
  63012. configurable: true
  63013. });
  63014. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63015. var rootUrlKey = "";
  63016. files.forEach(function (url) { return rootUrlKey += url; });
  63017. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63018. };
  63019. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63020. if (forcedExtension === void 0) { forcedExtension = null; }
  63021. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63022. };
  63023. // Methods
  63024. CubeTexture.prototype.delayLoad = function () {
  63025. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63026. return;
  63027. }
  63028. var scene = this.getScene();
  63029. if (!scene) {
  63030. return;
  63031. }
  63032. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63033. this._texture = this._getFromCache(this.url, this._noMipmap);
  63034. if (!this._texture) {
  63035. if (this._prefiltered) {
  63036. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63037. }
  63038. else {
  63039. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63040. }
  63041. }
  63042. };
  63043. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63044. return this._textureMatrix;
  63045. };
  63046. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63047. this._textureMatrix = value;
  63048. };
  63049. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63050. var texture = BABYLON.SerializationHelper.Parse(function () {
  63051. var prefiltered = false;
  63052. if (parsedTexture.prefiltered) {
  63053. prefiltered = parsedTexture.prefiltered;
  63054. }
  63055. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63056. }, parsedTexture, scene);
  63057. // Local Cubemaps
  63058. if (parsedTexture.boundingBoxPosition) {
  63059. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63060. }
  63061. if (parsedTexture.boundingBoxSize) {
  63062. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63063. }
  63064. // Animations
  63065. if (parsedTexture.animations) {
  63066. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63067. var parsedAnimation = parsedTexture.animations[animationIndex];
  63068. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63069. }
  63070. }
  63071. return texture;
  63072. };
  63073. CubeTexture.prototype.clone = function () {
  63074. var _this = this;
  63075. return BABYLON.SerializationHelper.Clone(function () {
  63076. var scene = _this.getScene();
  63077. if (!scene) {
  63078. return _this;
  63079. }
  63080. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63081. }, this);
  63082. };
  63083. __decorate([
  63084. BABYLON.serialize("rotationY")
  63085. ], CubeTexture.prototype, "_rotationY", void 0);
  63086. return CubeTexture;
  63087. }(BABYLON.BaseTexture));
  63088. BABYLON.CubeTexture = CubeTexture;
  63089. })(BABYLON || (BABYLON = {}));
  63090. //# sourceMappingURL=babylon.cubeTexture.js.map
  63091. var BABYLON;
  63092. (function (BABYLON) {
  63093. var RenderTargetTexture = /** @class */ (function (_super) {
  63094. __extends(RenderTargetTexture, _super);
  63095. /**
  63096. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63097. * or used a shadow, depth texture...
  63098. * @param name The friendly name of the texture
  63099. * @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)
  63100. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63101. * @param generateMipMaps True if mip maps need to be generated after render.
  63102. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63103. * @param type The type of the buffer in the RTT (int, half float, float...)
  63104. * @param isCube True if a cube texture needs to be created
  63105. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63106. * @param generateDepthBuffer True to generate a depth buffer
  63107. * @param generateStencilBuffer True to generate a stencil buffer
  63108. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63109. */
  63110. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63111. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63112. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63113. if (isCube === void 0) { isCube = false; }
  63114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63115. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63116. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63117. if (isMulti === void 0) { isMulti = false; }
  63118. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63119. _this.isCube = isCube;
  63120. /**
  63121. * Use this list to define the list of mesh you want to render.
  63122. */
  63123. _this.renderList = new Array();
  63124. _this.renderParticles = true;
  63125. _this.renderSprites = false;
  63126. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63127. _this.ignoreCameraViewport = false;
  63128. // Events
  63129. /**
  63130. * An event triggered when the texture is unbind.
  63131. */
  63132. _this.onBeforeBindObservable = new BABYLON.Observable();
  63133. /**
  63134. * An event triggered when the texture is unbind.
  63135. */
  63136. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63137. /**
  63138. * An event triggered before rendering the texture
  63139. */
  63140. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63141. /**
  63142. * An event triggered after rendering the texture
  63143. */
  63144. _this.onAfterRenderObservable = new BABYLON.Observable();
  63145. /**
  63146. * An event triggered after the texture clear
  63147. */
  63148. _this.onClearObservable = new BABYLON.Observable();
  63149. _this._currentRefreshId = -1;
  63150. _this._refreshRate = 1;
  63151. _this._samples = 1;
  63152. /**
  63153. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63154. * It must define where the camera used to render the texture is set
  63155. */
  63156. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63157. scene = _this.getScene();
  63158. if (!scene) {
  63159. return _this;
  63160. }
  63161. _this._engine = scene.getEngine();
  63162. _this.name = name;
  63163. _this.isRenderTarget = true;
  63164. _this._initialSizeParameter = size;
  63165. _this._processSizeParameter(size);
  63166. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63167. });
  63168. _this._generateMipMaps = generateMipMaps ? true : false;
  63169. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63170. // Rendering groups
  63171. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63172. if (isMulti) {
  63173. return _this;
  63174. }
  63175. _this._renderTargetOptions = {
  63176. generateMipMaps: generateMipMaps,
  63177. type: type,
  63178. samplingMode: samplingMode,
  63179. generateDepthBuffer: generateDepthBuffer,
  63180. generateStencilBuffer: generateStencilBuffer
  63181. };
  63182. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63183. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63184. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63185. }
  63186. if (isCube) {
  63187. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63188. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63189. _this._textureMatrix = BABYLON.Matrix.Identity();
  63190. }
  63191. else {
  63192. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63193. }
  63194. return _this;
  63195. }
  63196. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63197. get: function () {
  63198. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63199. },
  63200. enumerable: true,
  63201. configurable: true
  63202. });
  63203. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63204. get: function () {
  63205. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63206. },
  63207. enumerable: true,
  63208. configurable: true
  63209. });
  63210. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63211. get: function () {
  63212. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63213. },
  63214. enumerable: true,
  63215. configurable: true
  63216. });
  63217. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63218. set: function (callback) {
  63219. if (this._onAfterUnbindObserver) {
  63220. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63221. }
  63222. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63223. },
  63224. enumerable: true,
  63225. configurable: true
  63226. });
  63227. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63228. set: function (callback) {
  63229. if (this._onBeforeRenderObserver) {
  63230. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63231. }
  63232. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63233. },
  63234. enumerable: true,
  63235. configurable: true
  63236. });
  63237. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63238. set: function (callback) {
  63239. if (this._onAfterRenderObserver) {
  63240. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63241. }
  63242. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63243. },
  63244. enumerable: true,
  63245. configurable: true
  63246. });
  63247. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63248. set: function (callback) {
  63249. if (this._onClearObserver) {
  63250. this.onClearObservable.remove(this._onClearObserver);
  63251. }
  63252. this._onClearObserver = this.onClearObservable.add(callback);
  63253. },
  63254. enumerable: true,
  63255. configurable: true
  63256. });
  63257. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63258. get: function () {
  63259. return this._renderTargetOptions;
  63260. },
  63261. enumerable: true,
  63262. configurable: true
  63263. });
  63264. RenderTargetTexture.prototype._onRatioRescale = function () {
  63265. if (this._sizeRatio) {
  63266. this.resize(this._initialSizeParameter);
  63267. }
  63268. };
  63269. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63270. get: function () {
  63271. return this._boundingBoxSize;
  63272. },
  63273. /**
  63274. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63275. * When defined, the cubemap will switch to local mode
  63276. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63277. * @example https://www.babylonjs-playground.com/#RNASML
  63278. */
  63279. set: function (value) {
  63280. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63281. return;
  63282. }
  63283. this._boundingBoxSize = value;
  63284. var scene = this.getScene();
  63285. if (scene) {
  63286. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63287. }
  63288. },
  63289. enumerable: true,
  63290. configurable: true
  63291. });
  63292. /**
  63293. * Creates a depth stencil texture.
  63294. * This is only available in WebGL 2 or with the depth texture extension available.
  63295. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63296. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63297. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63298. */
  63299. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63300. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63301. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63302. if (generateStencil === void 0) { generateStencil = false; }
  63303. if (!this.getScene()) {
  63304. return;
  63305. }
  63306. var engine = this.getScene().getEngine();
  63307. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63308. bilinearFiltering: bilinearFiltering,
  63309. comparisonFunction: comparisonFunction,
  63310. generateStencil: generateStencil,
  63311. isCube: this.isCube
  63312. });
  63313. engine.setFrameBufferDepthStencilTexture(this);
  63314. };
  63315. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63316. if (size.ratio) {
  63317. this._sizeRatio = size.ratio;
  63318. this._size = {
  63319. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63320. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63321. };
  63322. }
  63323. else {
  63324. this._size = size;
  63325. }
  63326. };
  63327. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63328. get: function () {
  63329. return this._samples;
  63330. },
  63331. set: function (value) {
  63332. if (this._samples === value) {
  63333. return;
  63334. }
  63335. var scene = this.getScene();
  63336. if (!scene) {
  63337. return;
  63338. }
  63339. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63340. },
  63341. enumerable: true,
  63342. configurable: true
  63343. });
  63344. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63345. this._currentRefreshId = -1;
  63346. };
  63347. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63348. get: function () {
  63349. return this._refreshRate;
  63350. },
  63351. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63352. set: function (value) {
  63353. this._refreshRate = value;
  63354. this.resetRefreshCounter();
  63355. },
  63356. enumerable: true,
  63357. configurable: true
  63358. });
  63359. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63360. if (!this._postProcessManager) {
  63361. var scene = this.getScene();
  63362. if (!scene) {
  63363. return;
  63364. }
  63365. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63366. this._postProcesses = new Array();
  63367. }
  63368. this._postProcesses.push(postProcess);
  63369. this._postProcesses[0].autoClear = false;
  63370. };
  63371. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63372. if (!this._postProcesses) {
  63373. return;
  63374. }
  63375. if (dispose) {
  63376. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63377. var postProcess = _a[_i];
  63378. postProcess.dispose();
  63379. }
  63380. }
  63381. this._postProcesses = [];
  63382. };
  63383. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63384. if (!this._postProcesses) {
  63385. return;
  63386. }
  63387. var index = this._postProcesses.indexOf(postProcess);
  63388. if (index === -1) {
  63389. return;
  63390. }
  63391. this._postProcesses.splice(index, 1);
  63392. if (this._postProcesses.length > 0) {
  63393. this._postProcesses[0].autoClear = false;
  63394. }
  63395. };
  63396. RenderTargetTexture.prototype._shouldRender = function () {
  63397. if (this._currentRefreshId === -1) { // At least render once
  63398. this._currentRefreshId = 1;
  63399. return true;
  63400. }
  63401. if (this.refreshRate === this._currentRefreshId) {
  63402. this._currentRefreshId = 1;
  63403. return true;
  63404. }
  63405. this._currentRefreshId++;
  63406. return false;
  63407. };
  63408. RenderTargetTexture.prototype.getRenderSize = function () {
  63409. if (this._size.width) {
  63410. return this._size.width;
  63411. }
  63412. return this._size;
  63413. };
  63414. RenderTargetTexture.prototype.getRenderWidth = function () {
  63415. if (this._size.width) {
  63416. return this._size.width;
  63417. }
  63418. return this._size;
  63419. };
  63420. RenderTargetTexture.prototype.getRenderHeight = function () {
  63421. if (this._size.width) {
  63422. return this._size.height;
  63423. }
  63424. return this._size;
  63425. };
  63426. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63427. get: function () {
  63428. return true;
  63429. },
  63430. enumerable: true,
  63431. configurable: true
  63432. });
  63433. RenderTargetTexture.prototype.scale = function (ratio) {
  63434. var newSize = this.getRenderSize() * ratio;
  63435. this.resize(newSize);
  63436. };
  63437. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63438. if (this.isCube) {
  63439. return this._textureMatrix;
  63440. }
  63441. return _super.prototype.getReflectionTextureMatrix.call(this);
  63442. };
  63443. RenderTargetTexture.prototype.resize = function (size) {
  63444. this.releaseInternalTexture();
  63445. var scene = this.getScene();
  63446. if (!scene) {
  63447. return;
  63448. }
  63449. this._processSizeParameter(size);
  63450. if (this.isCube) {
  63451. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63452. }
  63453. else {
  63454. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63455. }
  63456. };
  63457. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63458. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63459. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63460. var scene = this.getScene();
  63461. if (!scene) {
  63462. return;
  63463. }
  63464. var engine = scene.getEngine();
  63465. if (this.useCameraPostProcesses !== undefined) {
  63466. useCameraPostProcess = this.useCameraPostProcesses;
  63467. }
  63468. if (this._waitingRenderList) {
  63469. this.renderList = [];
  63470. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63471. var id = this._waitingRenderList[index];
  63472. var mesh_1 = scene.getMeshByID(id);
  63473. if (mesh_1) {
  63474. this.renderList.push(mesh_1);
  63475. }
  63476. }
  63477. delete this._waitingRenderList;
  63478. }
  63479. // Is predicate defined?
  63480. if (this.renderListPredicate) {
  63481. if (this.renderList) {
  63482. this.renderList.splice(0); // Clear previous renderList
  63483. }
  63484. else {
  63485. this.renderList = [];
  63486. }
  63487. var scene = this.getScene();
  63488. if (!scene) {
  63489. return;
  63490. }
  63491. var sceneMeshes = scene.meshes;
  63492. for (var index = 0; index < sceneMeshes.length; index++) {
  63493. var mesh = sceneMeshes[index];
  63494. if (this.renderListPredicate(mesh)) {
  63495. this.renderList.push(mesh);
  63496. }
  63497. }
  63498. }
  63499. this.onBeforeBindObservable.notifyObservers(this);
  63500. // Set custom projection.
  63501. // Needs to be before binding to prevent changing the aspect ratio.
  63502. var camera;
  63503. if (this.activeCamera) {
  63504. camera = this.activeCamera;
  63505. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63506. if (this.activeCamera !== scene.activeCamera) {
  63507. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63508. }
  63509. }
  63510. else {
  63511. camera = scene.activeCamera;
  63512. if (camera) {
  63513. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63514. }
  63515. }
  63516. // Prepare renderingManager
  63517. this._renderingManager.reset();
  63518. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63519. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63520. var sceneRenderId = scene.getRenderId();
  63521. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63522. var mesh = currentRenderList[meshIndex];
  63523. if (mesh) {
  63524. if (!mesh.isReady(this.refreshRate === 0)) {
  63525. this.resetRefreshCounter();
  63526. continue;
  63527. }
  63528. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63529. var isMasked = void 0;
  63530. if (!this.renderList && camera) {
  63531. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63532. }
  63533. else {
  63534. isMasked = false;
  63535. }
  63536. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63537. mesh._activate(sceneRenderId);
  63538. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63539. var subMesh = mesh.subMeshes[subIndex];
  63540. scene._activeIndices.addCount(subMesh.indexCount, false);
  63541. this._renderingManager.dispatch(subMesh, mesh);
  63542. }
  63543. }
  63544. }
  63545. }
  63546. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63547. var particleSystem = scene.particleSystems[particleIndex];
  63548. var emitter = particleSystem.emitter;
  63549. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63550. continue;
  63551. }
  63552. if (currentRenderList.indexOf(emitter) >= 0) {
  63553. this._renderingManager.dispatchParticles(particleSystem);
  63554. }
  63555. }
  63556. if (this.isCube) {
  63557. for (var face = 0; face < 6; face++) {
  63558. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63559. scene.incrementRenderId();
  63560. scene.resetCachedMaterial();
  63561. }
  63562. }
  63563. else {
  63564. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63565. }
  63566. this.onAfterUnbindObservable.notifyObservers(this);
  63567. if (scene.activeCamera) {
  63568. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63569. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63570. }
  63571. engine.setViewport(scene.activeCamera.viewport);
  63572. }
  63573. scene.resetCachedMaterial();
  63574. };
  63575. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63576. var minimum = 128;
  63577. var x = renderDimension * scale;
  63578. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63579. // Ensure we don't exceed the render dimension (while staying POT)
  63580. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63581. };
  63582. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63583. var _this = this;
  63584. if (!this._texture) {
  63585. return;
  63586. }
  63587. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63588. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63589. });
  63590. };
  63591. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63592. var scene = this.getScene();
  63593. if (!scene) {
  63594. return;
  63595. }
  63596. var engine = scene.getEngine();
  63597. if (!this._texture) {
  63598. return;
  63599. }
  63600. // Bind
  63601. if (this._postProcessManager) {
  63602. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63603. }
  63604. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63605. if (this._texture) {
  63606. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63607. }
  63608. }
  63609. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63610. // Clear
  63611. if (this.onClearObservable.hasObservers()) {
  63612. this.onClearObservable.notifyObservers(engine);
  63613. }
  63614. else {
  63615. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63616. }
  63617. if (!this._doNotChangeAspectRatio) {
  63618. scene.updateTransformMatrix(true);
  63619. }
  63620. // Render
  63621. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63622. if (this._postProcessManager) {
  63623. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63624. }
  63625. else if (useCameraPostProcess) {
  63626. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63627. }
  63628. if (!this._doNotChangeAspectRatio) {
  63629. scene.updateTransformMatrix(true);
  63630. }
  63631. // Dump ?
  63632. if (dumpForDebug) {
  63633. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63634. }
  63635. // Unbind
  63636. if (!this.isCube || faceIndex === 5) {
  63637. if (this.isCube) {
  63638. if (faceIndex === 5) {
  63639. engine.generateMipMapsForCubemap(this._texture);
  63640. }
  63641. }
  63642. this.unbindFrameBuffer(engine, faceIndex);
  63643. }
  63644. else {
  63645. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63646. }
  63647. };
  63648. /**
  63649. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63650. * This allowed control for front to back rendering or reversly depending of the special needs.
  63651. *
  63652. * @param renderingGroupId The rendering group id corresponding to its index
  63653. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63654. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63655. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63656. */
  63657. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63658. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63659. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63660. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63661. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63662. };
  63663. /**
  63664. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63665. *
  63666. * @param renderingGroupId The rendering group id corresponding to its index
  63667. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63668. */
  63669. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63670. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63671. };
  63672. RenderTargetTexture.prototype.clone = function () {
  63673. var textureSize = this.getSize();
  63674. 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);
  63675. // Base texture
  63676. newTexture.hasAlpha = this.hasAlpha;
  63677. newTexture.level = this.level;
  63678. // RenderTarget Texture
  63679. newTexture.coordinatesMode = this.coordinatesMode;
  63680. if (this.renderList) {
  63681. newTexture.renderList = this.renderList.slice(0);
  63682. }
  63683. return newTexture;
  63684. };
  63685. RenderTargetTexture.prototype.serialize = function () {
  63686. if (!this.name) {
  63687. return null;
  63688. }
  63689. var serializationObject = _super.prototype.serialize.call(this);
  63690. serializationObject.renderTargetSize = this.getRenderSize();
  63691. serializationObject.renderList = [];
  63692. if (this.renderList) {
  63693. for (var index = 0; index < this.renderList.length; index++) {
  63694. serializationObject.renderList.push(this.renderList[index].id);
  63695. }
  63696. }
  63697. return serializationObject;
  63698. };
  63699. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63700. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63701. var objBuffer = this.getInternalTexture();
  63702. var scene = this.getScene();
  63703. if (objBuffer && scene) {
  63704. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63705. }
  63706. };
  63707. RenderTargetTexture.prototype.dispose = function () {
  63708. if (this._postProcessManager) {
  63709. this._postProcessManager.dispose();
  63710. this._postProcessManager = null;
  63711. }
  63712. this.clearPostProcesses(true);
  63713. if (this._resizeObserver) {
  63714. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63715. this._resizeObserver = null;
  63716. }
  63717. this.renderList = null;
  63718. // Remove from custom render targets
  63719. var scene = this.getScene();
  63720. if (!scene) {
  63721. return;
  63722. }
  63723. var index = scene.customRenderTargets.indexOf(this);
  63724. if (index >= 0) {
  63725. scene.customRenderTargets.splice(index, 1);
  63726. }
  63727. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63728. var camera = _a[_i];
  63729. index = camera.customRenderTargets.indexOf(this);
  63730. if (index >= 0) {
  63731. camera.customRenderTargets.splice(index, 1);
  63732. }
  63733. }
  63734. _super.prototype.dispose.call(this);
  63735. };
  63736. RenderTargetTexture.prototype._rebuild = function () {
  63737. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63738. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63739. }
  63740. if (this._postProcessManager) {
  63741. this._postProcessManager._rebuild();
  63742. }
  63743. };
  63744. /**
  63745. * Clear the info related to rendering groups preventing retention point in material dispose.
  63746. */
  63747. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63748. if (this._renderingManager) {
  63749. this._renderingManager.freeRenderingGroups();
  63750. }
  63751. };
  63752. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63753. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63754. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63755. return RenderTargetTexture;
  63756. }(BABYLON.Texture));
  63757. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63758. })(BABYLON || (BABYLON = {}));
  63759. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63760. var BABYLON;
  63761. (function (BABYLON) {
  63762. ;
  63763. var MultiRenderTarget = /** @class */ (function (_super) {
  63764. __extends(MultiRenderTarget, _super);
  63765. function MultiRenderTarget(name, size, count, scene, options) {
  63766. var _this = this;
  63767. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63768. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63769. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63770. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63771. _this._engine = scene.getEngine();
  63772. if (!_this.isSupported) {
  63773. _this.dispose();
  63774. return;
  63775. }
  63776. var types = [];
  63777. var samplingModes = [];
  63778. for (var i = 0; i < count; i++) {
  63779. if (options && options.types && options.types[i] !== undefined) {
  63780. types.push(options.types[i]);
  63781. }
  63782. else {
  63783. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63784. }
  63785. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63786. samplingModes.push(options.samplingModes[i]);
  63787. }
  63788. else {
  63789. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63790. }
  63791. }
  63792. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63793. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63794. _this._size = size;
  63795. _this._multiRenderTargetOptions = {
  63796. samplingModes: samplingModes,
  63797. generateMipMaps: generateMipMaps,
  63798. generateDepthBuffer: generateDepthBuffer,
  63799. generateStencilBuffer: generateStencilBuffer,
  63800. generateDepthTexture: generateDepthTexture,
  63801. types: types,
  63802. textureCount: count
  63803. };
  63804. _this._createInternalTextures();
  63805. _this._createTextures();
  63806. return _this;
  63807. }
  63808. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63809. get: function () {
  63810. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63811. },
  63812. enumerable: true,
  63813. configurable: true
  63814. });
  63815. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63816. get: function () {
  63817. return this._textures;
  63818. },
  63819. enumerable: true,
  63820. configurable: true
  63821. });
  63822. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63823. get: function () {
  63824. return this._textures[this._textures.length - 1];
  63825. },
  63826. enumerable: true,
  63827. configurable: true
  63828. });
  63829. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63830. set: function (wrap) {
  63831. if (this._textures) {
  63832. for (var i = 0; i < this._textures.length; i++) {
  63833. this._textures[i].wrapU = wrap;
  63834. }
  63835. }
  63836. },
  63837. enumerable: true,
  63838. configurable: true
  63839. });
  63840. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63841. set: function (wrap) {
  63842. if (this._textures) {
  63843. for (var i = 0; i < this._textures.length; i++) {
  63844. this._textures[i].wrapV = wrap;
  63845. }
  63846. }
  63847. },
  63848. enumerable: true,
  63849. configurable: true
  63850. });
  63851. MultiRenderTarget.prototype._rebuild = function () {
  63852. this.releaseInternalTextures();
  63853. this._createInternalTextures();
  63854. for (var i = 0; i < this._internalTextures.length; i++) {
  63855. var texture = this._textures[i];
  63856. texture._texture = this._internalTextures[i];
  63857. }
  63858. // Keeps references to frame buffer and stencil/depth buffer
  63859. this._texture = this._internalTextures[0];
  63860. };
  63861. MultiRenderTarget.prototype._createInternalTextures = function () {
  63862. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63863. };
  63864. MultiRenderTarget.prototype._createTextures = function () {
  63865. this._textures = [];
  63866. for (var i = 0; i < this._internalTextures.length; i++) {
  63867. var texture = new BABYLON.Texture(null, this.getScene());
  63868. texture._texture = this._internalTextures[i];
  63869. this._textures.push(texture);
  63870. }
  63871. // Keeps references to frame buffer and stencil/depth buffer
  63872. this._texture = this._internalTextures[0];
  63873. };
  63874. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63875. get: function () {
  63876. return this._samples;
  63877. },
  63878. set: function (value) {
  63879. if (this._samples === value) {
  63880. return;
  63881. }
  63882. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63883. },
  63884. enumerable: true,
  63885. configurable: true
  63886. });
  63887. MultiRenderTarget.prototype.resize = function (size) {
  63888. this.releaseInternalTextures();
  63889. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63890. this._createInternalTextures();
  63891. };
  63892. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63893. var _this = this;
  63894. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63895. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63896. });
  63897. };
  63898. MultiRenderTarget.prototype.dispose = function () {
  63899. this.releaseInternalTextures();
  63900. _super.prototype.dispose.call(this);
  63901. };
  63902. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63903. if (!this._internalTextures) {
  63904. return;
  63905. }
  63906. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63907. if (this._internalTextures[i] !== undefined) {
  63908. this._internalTextures[i].dispose();
  63909. this._internalTextures.splice(i, 1);
  63910. }
  63911. }
  63912. };
  63913. return MultiRenderTarget;
  63914. }(BABYLON.RenderTargetTexture));
  63915. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63916. })(BABYLON || (BABYLON = {}));
  63917. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63918. var BABYLON;
  63919. (function (BABYLON) {
  63920. var MirrorTexture = /** @class */ (function (_super) {
  63921. __extends(MirrorTexture, _super);
  63922. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63923. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63925. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63926. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63927. _this.scene = scene;
  63928. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63929. _this._transformMatrix = BABYLON.Matrix.Zero();
  63930. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63931. _this._adaptiveBlurKernel = 0;
  63932. _this._blurKernelX = 0;
  63933. _this._blurKernelY = 0;
  63934. _this._blurRatio = 1.0;
  63935. _this.ignoreCameraViewport = true;
  63936. _this._updateGammaSpace();
  63937. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63938. _this._updateGammaSpace;
  63939. });
  63940. _this.onBeforeRenderObservable.add(function () {
  63941. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63942. _this._savedViewMatrix = scene.getViewMatrix();
  63943. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63944. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63945. scene.clipPlane = _this.mirrorPlane;
  63946. scene.getEngine().cullBackFaces = false;
  63947. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63948. });
  63949. _this.onAfterRenderObservable.add(function () {
  63950. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63951. scene.getEngine().cullBackFaces = true;
  63952. scene._mirroredCameraPosition = null;
  63953. delete scene.clipPlane;
  63954. });
  63955. return _this;
  63956. }
  63957. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63958. get: function () {
  63959. return this._blurRatio;
  63960. },
  63961. set: function (value) {
  63962. if (this._blurRatio === value) {
  63963. return;
  63964. }
  63965. this._blurRatio = value;
  63966. this._preparePostProcesses();
  63967. },
  63968. enumerable: true,
  63969. configurable: true
  63970. });
  63971. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63972. set: function (value) {
  63973. this._adaptiveBlurKernel = value;
  63974. this._autoComputeBlurKernel();
  63975. },
  63976. enumerable: true,
  63977. configurable: true
  63978. });
  63979. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63980. set: function (value) {
  63981. this.blurKernelX = value;
  63982. this.blurKernelY = value;
  63983. },
  63984. enumerable: true,
  63985. configurable: true
  63986. });
  63987. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63988. get: function () {
  63989. return this._blurKernelX;
  63990. },
  63991. set: function (value) {
  63992. if (this._blurKernelX === value) {
  63993. return;
  63994. }
  63995. this._blurKernelX = value;
  63996. this._preparePostProcesses();
  63997. },
  63998. enumerable: true,
  63999. configurable: true
  64000. });
  64001. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64002. get: function () {
  64003. return this._blurKernelY;
  64004. },
  64005. set: function (value) {
  64006. if (this._blurKernelY === value) {
  64007. return;
  64008. }
  64009. this._blurKernelY = value;
  64010. this._preparePostProcesses();
  64011. },
  64012. enumerable: true,
  64013. configurable: true
  64014. });
  64015. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64016. var engine = this.getScene().getEngine();
  64017. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64018. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64019. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64020. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64021. };
  64022. MirrorTexture.prototype._onRatioRescale = function () {
  64023. if (this._sizeRatio) {
  64024. this.resize(this._initialSizeParameter);
  64025. if (!this._adaptiveBlurKernel) {
  64026. this._preparePostProcesses();
  64027. }
  64028. }
  64029. if (this._adaptiveBlurKernel) {
  64030. this._autoComputeBlurKernel();
  64031. }
  64032. };
  64033. MirrorTexture.prototype._updateGammaSpace = function () {
  64034. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64035. };
  64036. MirrorTexture.prototype._preparePostProcesses = function () {
  64037. this.clearPostProcesses(true);
  64038. if (this._blurKernelX && this._blurKernelY) {
  64039. var engine = this.getScene().getEngine();
  64040. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64041. 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);
  64042. this._blurX.autoClear = false;
  64043. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64044. this._blurX.inputTexture = this._texture;
  64045. }
  64046. else {
  64047. this._blurX.alwaysForcePOT = true;
  64048. }
  64049. 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);
  64050. this._blurY.autoClear = false;
  64051. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64052. this.addPostProcess(this._blurX);
  64053. this.addPostProcess(this._blurY);
  64054. }
  64055. else {
  64056. if (this._blurY) {
  64057. this.removePostProcess(this._blurY);
  64058. this._blurY.dispose();
  64059. this._blurY = null;
  64060. }
  64061. if (this._blurX) {
  64062. this.removePostProcess(this._blurX);
  64063. this._blurX.dispose();
  64064. this._blurX = null;
  64065. }
  64066. }
  64067. };
  64068. MirrorTexture.prototype.clone = function () {
  64069. var scene = this.getScene();
  64070. if (!scene) {
  64071. return this;
  64072. }
  64073. var textureSize = this.getSize();
  64074. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64075. // Base texture
  64076. newTexture.hasAlpha = this.hasAlpha;
  64077. newTexture.level = this.level;
  64078. // Mirror Texture
  64079. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64080. if (this.renderList) {
  64081. newTexture.renderList = this.renderList.slice(0);
  64082. }
  64083. return newTexture;
  64084. };
  64085. MirrorTexture.prototype.serialize = function () {
  64086. if (!this.name) {
  64087. return null;
  64088. }
  64089. var serializationObject = _super.prototype.serialize.call(this);
  64090. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64091. return serializationObject;
  64092. };
  64093. MirrorTexture.prototype.dispose = function () {
  64094. _super.prototype.dispose.call(this);
  64095. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64096. };
  64097. return MirrorTexture;
  64098. }(BABYLON.RenderTargetTexture));
  64099. BABYLON.MirrorTexture = MirrorTexture;
  64100. })(BABYLON || (BABYLON = {}));
  64101. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64102. var BABYLON;
  64103. (function (BABYLON) {
  64104. /**
  64105. * Creates a refraction texture used by refraction channel of the standard material.
  64106. * @param name the texture name
  64107. * @param size size of the underlying texture
  64108. * @param scene root scene
  64109. */
  64110. var RefractionTexture = /** @class */ (function (_super) {
  64111. __extends(RefractionTexture, _super);
  64112. function RefractionTexture(name, size, scene, generateMipMaps) {
  64113. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64114. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64115. _this.depth = 2.0;
  64116. _this.onBeforeRenderObservable.add(function () {
  64117. scene.clipPlane = _this.refractionPlane;
  64118. });
  64119. _this.onAfterRenderObservable.add(function () {
  64120. delete scene.clipPlane;
  64121. });
  64122. return _this;
  64123. }
  64124. RefractionTexture.prototype.clone = function () {
  64125. var scene = this.getScene();
  64126. if (!scene) {
  64127. return this;
  64128. }
  64129. var textureSize = this.getSize();
  64130. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64131. // Base texture
  64132. newTexture.hasAlpha = this.hasAlpha;
  64133. newTexture.level = this.level;
  64134. // Refraction Texture
  64135. newTexture.refractionPlane = this.refractionPlane.clone();
  64136. if (this.renderList) {
  64137. newTexture.renderList = this.renderList.slice(0);
  64138. }
  64139. newTexture.depth = this.depth;
  64140. return newTexture;
  64141. };
  64142. RefractionTexture.prototype.serialize = function () {
  64143. if (!this.name) {
  64144. return null;
  64145. }
  64146. var serializationObject = _super.prototype.serialize.call(this);
  64147. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64148. serializationObject.depth = this.depth;
  64149. return serializationObject;
  64150. };
  64151. return RefractionTexture;
  64152. }(BABYLON.RenderTargetTexture));
  64153. BABYLON.RefractionTexture = RefractionTexture;
  64154. })(BABYLON || (BABYLON = {}));
  64155. //# sourceMappingURL=babylon.refractionTexture.js.map
  64156. var BABYLON;
  64157. (function (BABYLON) {
  64158. /**
  64159. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64160. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64161. */
  64162. var DynamicTexture = /** @class */ (function (_super) {
  64163. __extends(DynamicTexture, _super);
  64164. /**
  64165. * Creates a {BABYLON.DynamicTexture}
  64166. * @param name defines the name of the texture
  64167. * @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
  64168. * @param scene defines the scene where you want the texture
  64169. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64170. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64171. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64172. */
  64173. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64174. if (scene === void 0) { scene = null; }
  64175. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64176. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64177. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64178. _this.name = name;
  64179. _this._engine = _this.getScene().getEngine();
  64180. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64181. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64182. _this._generateMipMaps = generateMipMaps;
  64183. if (options.getContext) {
  64184. _this._canvas = options;
  64185. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64186. }
  64187. else {
  64188. _this._canvas = document.createElement("canvas");
  64189. if (options.width || options.width === 0) {
  64190. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64191. }
  64192. else {
  64193. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64194. }
  64195. }
  64196. var textureSize = _this.getSize();
  64197. _this._canvas.width = textureSize.width;
  64198. _this._canvas.height = textureSize.height;
  64199. _this._context = _this._canvas.getContext("2d");
  64200. return _this;
  64201. }
  64202. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64203. /**
  64204. * Gets the current state of canRescale
  64205. */
  64206. get: function () {
  64207. return true;
  64208. },
  64209. enumerable: true,
  64210. configurable: true
  64211. });
  64212. DynamicTexture.prototype._recreate = function (textureSize) {
  64213. this._canvas.width = textureSize.width;
  64214. this._canvas.height = textureSize.height;
  64215. this.releaseInternalTexture();
  64216. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64217. };
  64218. /**
  64219. * Scales the texture
  64220. * @param ratio the scale factor to apply to both width and height
  64221. */
  64222. DynamicTexture.prototype.scale = function (ratio) {
  64223. var textureSize = this.getSize();
  64224. textureSize.width *= ratio;
  64225. textureSize.height *= ratio;
  64226. this._recreate(textureSize);
  64227. };
  64228. /**
  64229. * Resizes the texture
  64230. * @param width the new width
  64231. * @param height the new height
  64232. */
  64233. DynamicTexture.prototype.scaleTo = function (width, height) {
  64234. var textureSize = this.getSize();
  64235. textureSize.width = width;
  64236. textureSize.height = height;
  64237. this._recreate(textureSize);
  64238. };
  64239. /**
  64240. * Gets the context of the canvas used by the texture
  64241. * @returns the canvas context of the dynamic texture
  64242. */
  64243. DynamicTexture.prototype.getContext = function () {
  64244. return this._context;
  64245. };
  64246. /**
  64247. * Clears the texture
  64248. */
  64249. DynamicTexture.prototype.clear = function () {
  64250. var size = this.getSize();
  64251. this._context.fillRect(0, 0, size.width, size.height);
  64252. };
  64253. /**
  64254. * Updates the texture
  64255. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64256. */
  64257. DynamicTexture.prototype.update = function (invertY) {
  64258. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64259. };
  64260. /**
  64261. * Draws text onto the texture
  64262. * @param text defines the text to be drawn
  64263. * @param x defines the placement of the text from the left
  64264. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64265. * @param font defines the font to be used with font-style, font-size, font-name
  64266. * @param color defines the color used for the text
  64267. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64268. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64269. * @param update defines whether texture is immediately update (default is true)
  64270. */
  64271. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64272. if (update === void 0) { update = true; }
  64273. var size = this.getSize();
  64274. if (clearColor) {
  64275. this._context.fillStyle = clearColor;
  64276. this._context.fillRect(0, 0, size.width, size.height);
  64277. }
  64278. this._context.font = font;
  64279. if (x === null || x === undefined) {
  64280. var textSize = this._context.measureText(text);
  64281. x = (size.width - textSize.width) / 2;
  64282. }
  64283. if (y === null || y === undefined) {
  64284. var fontSize = parseInt((font.replace(/\D/g, '')));
  64285. ;
  64286. y = (size.height / 2) + (fontSize / 3.65);
  64287. }
  64288. this._context.fillStyle = color;
  64289. this._context.fillText(text, x, y);
  64290. if (update) {
  64291. this.update(invertY);
  64292. }
  64293. };
  64294. /**
  64295. * Clones the texture
  64296. * @returns the clone of the texture.
  64297. */
  64298. DynamicTexture.prototype.clone = function () {
  64299. var scene = this.getScene();
  64300. if (!scene) {
  64301. return this;
  64302. }
  64303. var textureSize = this.getSize();
  64304. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64305. // Base texture
  64306. newTexture.hasAlpha = this.hasAlpha;
  64307. newTexture.level = this.level;
  64308. // Dynamic Texture
  64309. newTexture.wrapU = this.wrapU;
  64310. newTexture.wrapV = this.wrapV;
  64311. return newTexture;
  64312. };
  64313. /** @hidden */
  64314. DynamicTexture.prototype._rebuild = function () {
  64315. this.update();
  64316. };
  64317. return DynamicTexture;
  64318. }(BABYLON.Texture));
  64319. BABYLON.DynamicTexture = DynamicTexture;
  64320. })(BABYLON || (BABYLON = {}));
  64321. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64322. var BABYLON;
  64323. (function (BABYLON) {
  64324. var VideoTexture = /** @class */ (function (_super) {
  64325. __extends(VideoTexture, _super);
  64326. /**
  64327. * Creates a video texture.
  64328. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64329. * @param {string | null} name optional name, will detect from video source, if not defined
  64330. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64331. * @param {BABYLON.Scene} scene is obviously the current scene.
  64332. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64333. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64334. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64335. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64336. */
  64337. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64338. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64339. if (invertY === void 0) { invertY = false; }
  64340. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64341. if (settings === void 0) { settings = {
  64342. autoPlay: true,
  64343. loop: true,
  64344. autoUpdateTexture: true,
  64345. }; }
  64346. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64347. _this._stillImageCaptured = false;
  64348. _this._createInternalTexture = function () {
  64349. if (_this._texture != null) {
  64350. return;
  64351. }
  64352. if (!_this._engine.needPOTTextures ||
  64353. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64354. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64355. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64356. }
  64357. else {
  64358. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64359. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64360. _this._generateMipMaps = false;
  64361. }
  64362. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64363. if (!_this.video.autoplay) {
  64364. var oldHandler_1 = _this.video.onplaying;
  64365. _this.video.onplaying = function () {
  64366. _this.video.onplaying = oldHandler_1;
  64367. _this._texture.isReady = true;
  64368. _this._updateInternalTexture();
  64369. _this.video.pause();
  64370. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64371. _this.onLoadObservable.notifyObservers(_this);
  64372. }
  64373. };
  64374. _this.video.play();
  64375. }
  64376. else {
  64377. _this._texture.isReady = true;
  64378. _this._updateInternalTexture();
  64379. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64380. _this.onLoadObservable.notifyObservers(_this);
  64381. }
  64382. }
  64383. };
  64384. _this.reset = function () {
  64385. if (_this._texture == null) {
  64386. return;
  64387. }
  64388. _this._texture.dispose();
  64389. _this._texture = null;
  64390. };
  64391. _this._updateInternalTexture = function (e) {
  64392. if (_this._texture == null || !_this._texture.isReady) {
  64393. return;
  64394. }
  64395. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64396. return;
  64397. }
  64398. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64399. };
  64400. _this._engine = _this.getScene().getEngine();
  64401. _this._generateMipMaps = generateMipMaps;
  64402. _this._samplingMode = samplingMode;
  64403. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64404. _this.name = name || _this._getName(src);
  64405. _this.video = _this._getVideo(src);
  64406. if (settings.autoPlay !== undefined) {
  64407. _this.video.autoplay = settings.autoPlay;
  64408. }
  64409. if (settings.loop !== undefined) {
  64410. _this.video.loop = settings.loop;
  64411. }
  64412. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64413. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64414. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64415. _this.video.addEventListener("emptied", _this.reset);
  64416. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64417. _this._createInternalTexture();
  64418. }
  64419. return _this;
  64420. }
  64421. VideoTexture.prototype._getName = function (src) {
  64422. if (src instanceof HTMLVideoElement) {
  64423. return src.currentSrc;
  64424. }
  64425. if (typeof src === "object") {
  64426. return src.toString();
  64427. }
  64428. return src;
  64429. };
  64430. ;
  64431. VideoTexture.prototype._getVideo = function (src) {
  64432. if (src instanceof HTMLVideoElement) {
  64433. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64434. return src;
  64435. }
  64436. var video = document.createElement("video");
  64437. if (typeof src === "string") {
  64438. BABYLON.Tools.SetCorsBehavior(src, video);
  64439. video.src = src;
  64440. }
  64441. else {
  64442. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64443. src.forEach(function (url) {
  64444. var source = document.createElement("source");
  64445. source.src = url;
  64446. video.appendChild(source);
  64447. });
  64448. }
  64449. return video;
  64450. };
  64451. ;
  64452. /**
  64453. * Internal method to initiate `update`.
  64454. */
  64455. VideoTexture.prototype._rebuild = function () {
  64456. this.update();
  64457. };
  64458. /**
  64459. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64460. */
  64461. VideoTexture.prototype.update = function () {
  64462. if (!this.autoUpdateTexture) {
  64463. // Expecting user to call `updateTexture` manually
  64464. return;
  64465. }
  64466. this.updateTexture(true);
  64467. };
  64468. /**
  64469. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64470. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64471. */
  64472. VideoTexture.prototype.updateTexture = function (isVisible) {
  64473. if (!isVisible) {
  64474. return;
  64475. }
  64476. if (this.video.paused && this._stillImageCaptured) {
  64477. return;
  64478. }
  64479. this._stillImageCaptured = true;
  64480. this._updateInternalTexture();
  64481. };
  64482. /**
  64483. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64484. * @param url New url.
  64485. */
  64486. VideoTexture.prototype.updateURL = function (url) {
  64487. this.video.src = url;
  64488. };
  64489. VideoTexture.prototype.dispose = function () {
  64490. _super.prototype.dispose.call(this);
  64491. this.video.removeEventListener("canplay", this._createInternalTexture);
  64492. this.video.removeEventListener("paused", this._updateInternalTexture);
  64493. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64494. this.video.removeEventListener("emptied", this.reset);
  64495. this.video.pause();
  64496. };
  64497. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64498. var video = document.createElement("video");
  64499. var constraintsDeviceId;
  64500. if (constraints && constraints.deviceId) {
  64501. constraintsDeviceId = {
  64502. exact: constraints.deviceId,
  64503. };
  64504. }
  64505. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64506. if (navigator.mediaDevices) {
  64507. navigator.mediaDevices.getUserMedia({ video: constraints })
  64508. .then(function (stream) {
  64509. if (video.mozSrcObject !== undefined) {
  64510. // hack for Firefox < 19
  64511. video.mozSrcObject = stream;
  64512. }
  64513. else {
  64514. video.srcObject = stream;
  64515. }
  64516. var onPlaying = function () {
  64517. if (onReady) {
  64518. onReady(new VideoTexture("video", video, scene, true, true));
  64519. }
  64520. video.removeEventListener("playing", onPlaying);
  64521. };
  64522. video.addEventListener("playing", onPlaying);
  64523. video.play();
  64524. })
  64525. .catch(function (err) {
  64526. BABYLON.Tools.Error(err.name);
  64527. });
  64528. }
  64529. else {
  64530. navigator.getUserMedia =
  64531. navigator.getUserMedia ||
  64532. navigator.webkitGetUserMedia ||
  64533. navigator.mozGetUserMedia ||
  64534. navigator.msGetUserMedia;
  64535. if (navigator.getUserMedia) {
  64536. navigator.getUserMedia({
  64537. video: {
  64538. deviceId: constraintsDeviceId,
  64539. width: {
  64540. min: (constraints && constraints.minWidth) || 256,
  64541. max: (constraints && constraints.maxWidth) || 640,
  64542. },
  64543. height: {
  64544. min: (constraints && constraints.minHeight) || 256,
  64545. max: (constraints && constraints.maxHeight) || 480,
  64546. },
  64547. },
  64548. }, function (stream) {
  64549. if (video.mozSrcObject !== undefined) {
  64550. // hack for Firefox < 19
  64551. video.mozSrcObject = stream;
  64552. }
  64553. else {
  64554. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64555. }
  64556. video.play();
  64557. if (onReady) {
  64558. onReady(new VideoTexture("video", video, scene, true, true));
  64559. }
  64560. }, function (e) {
  64561. BABYLON.Tools.Error(e.name);
  64562. });
  64563. }
  64564. }
  64565. };
  64566. return VideoTexture;
  64567. }(BABYLON.Texture));
  64568. BABYLON.VideoTexture = VideoTexture;
  64569. })(BABYLON || (BABYLON = {}));
  64570. //# sourceMappingURL=babylon.videoTexture.js.map
  64571. var BABYLON;
  64572. (function (BABYLON) {
  64573. var RawTexture = /** @class */ (function (_super) {
  64574. __extends(RawTexture, _super);
  64575. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64576. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64577. if (invertY === void 0) { invertY = false; }
  64578. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64579. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64580. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64581. _this.format = format;
  64582. _this._engine = scene.getEngine();
  64583. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64584. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64585. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64586. return _this;
  64587. }
  64588. RawTexture.prototype.update = function (data) {
  64589. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64590. };
  64591. // Statics
  64592. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64593. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64594. if (invertY === void 0) { invertY = false; }
  64595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64596. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64597. };
  64598. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64599. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64600. if (invertY === void 0) { invertY = false; }
  64601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64602. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64603. };
  64604. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64605. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64606. if (invertY === void 0) { invertY = false; }
  64607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64608. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64609. };
  64610. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64611. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64612. if (invertY === void 0) { invertY = false; }
  64613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64614. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64615. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64616. };
  64617. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64618. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64619. if (invertY === void 0) { invertY = false; }
  64620. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64621. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64622. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64623. };
  64624. return RawTexture;
  64625. }(BABYLON.Texture));
  64626. BABYLON.RawTexture = RawTexture;
  64627. })(BABYLON || (BABYLON = {}));
  64628. //# sourceMappingURL=babylon.rawTexture.js.map
  64629. var BABYLON;
  64630. (function (BABYLON) {
  64631. /**
  64632. * Class used to store 3D textures containing user data
  64633. */
  64634. var RawTexture3D = /** @class */ (function (_super) {
  64635. __extends(RawTexture3D, _super);
  64636. /**
  64637. * Create a new RawTexture3D
  64638. * @param data defines the data of the texture
  64639. * @param width defines the width of the texture
  64640. * @param height defines the height of the texture
  64641. * @param depth defines the depth of the texture
  64642. * @param format defines the texture format to use
  64643. * @param scene defines the hosting scene
  64644. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64645. * @param invertY defines if texture must be stored with Y axis inverted
  64646. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64647. */
  64648. function RawTexture3D(data, width, height, depth,
  64649. /** Gets or sets the texture format to use*/
  64650. format, scene, generateMipMaps, invertY, samplingMode) {
  64651. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64652. if (invertY === void 0) { invertY = false; }
  64653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64654. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64655. _this.format = format;
  64656. _this._engine = scene.getEngine();
  64657. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64658. _this.is3D = true;
  64659. return _this;
  64660. }
  64661. /**
  64662. * Update the texture with new data
  64663. * @param data defines the data to store in the texture
  64664. */
  64665. RawTexture3D.prototype.update = function (data) {
  64666. if (!this._texture) {
  64667. return;
  64668. }
  64669. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64670. };
  64671. return RawTexture3D;
  64672. }(BABYLON.Texture));
  64673. BABYLON.RawTexture3D = RawTexture3D;
  64674. })(BABYLON || (BABYLON = {}));
  64675. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64676. var BABYLON;
  64677. (function (BABYLON) {
  64678. /**
  64679. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64680. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64681. */
  64682. var PostProcess = /** @class */ (function () {
  64683. /**
  64684. * Creates a new instance PostProcess
  64685. * @param name The name of the PostProcess.
  64686. * @param fragmentUrl The url of the fragment shader to be used.
  64687. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64688. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64689. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64690. * @param camera The camera to apply the render pass to.
  64691. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64692. * @param engine The engine which the post process will be applied. (default: current engine)
  64693. * @param reusable If the post process can be reused on the same frame. (default: false)
  64694. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64695. * @param textureType Type of textures used when performing the post process. (default: 0)
  64696. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64697. * @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
  64698. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64699. */
  64700. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64702. if (defines === void 0) { defines = null; }
  64703. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64704. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64705. if (blockCompilation === void 0) { blockCompilation = false; }
  64706. this.name = name;
  64707. /**
  64708. * Width of the texture to apply the post process on
  64709. */
  64710. this.width = -1;
  64711. /**
  64712. * Height of the texture to apply the post process on
  64713. */
  64714. this.height = -1;
  64715. /**
  64716. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64717. */
  64718. this._outputTexture = null;
  64719. /**
  64720. * If the buffer needs to be cleared before applying the post process. (default: true)
  64721. * Should be set to false if shader will overwrite all previous pixels.
  64722. */
  64723. this.autoClear = true;
  64724. /**
  64725. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64726. */
  64727. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64728. /**
  64729. * Animations to be used for the post processing
  64730. */
  64731. this.animations = new Array();
  64732. /**
  64733. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64734. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64735. */
  64736. this.enablePixelPerfectMode = false;
  64737. /**
  64738. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64739. */
  64740. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64741. /**
  64742. * Force textures to be a power of two (default: false)
  64743. */
  64744. this.alwaysForcePOT = false;
  64745. /**
  64746. * Number of sample textures (default: 1)
  64747. */
  64748. this.samples = 1;
  64749. /**
  64750. * Modify the scale of the post process to be the same as the viewport (default: false)
  64751. */
  64752. this.adaptScaleToCurrentViewport = false;
  64753. this._reusable = false;
  64754. /**
  64755. * Smart array of input and output textures for the post process.
  64756. */
  64757. this._textures = new BABYLON.SmartArray(2);
  64758. /**
  64759. * The index in _textures that corresponds to the output texture.
  64760. */
  64761. this._currentRenderTextureInd = 0;
  64762. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64763. this._texelSize = BABYLON.Vector2.Zero();
  64764. // Events
  64765. /**
  64766. * An event triggered when the postprocess is activated.
  64767. */
  64768. this.onActivateObservable = new BABYLON.Observable();
  64769. /**
  64770. * An event triggered when the postprocess changes its size.
  64771. */
  64772. this.onSizeChangedObservable = new BABYLON.Observable();
  64773. /**
  64774. * An event triggered when the postprocess applies its effect.
  64775. */
  64776. this.onApplyObservable = new BABYLON.Observable();
  64777. /**
  64778. * An event triggered before rendering the postprocess
  64779. */
  64780. this.onBeforeRenderObservable = new BABYLON.Observable();
  64781. /**
  64782. * An event triggered after rendering the postprocess
  64783. */
  64784. this.onAfterRenderObservable = new BABYLON.Observable();
  64785. if (camera != null) {
  64786. this._camera = camera;
  64787. this._scene = camera.getScene();
  64788. camera.attachPostProcess(this);
  64789. this._engine = this._scene.getEngine();
  64790. this._scene.postProcesses.push(this);
  64791. }
  64792. else if (engine) {
  64793. this._engine = engine;
  64794. this._engine.postProcesses.push(this);
  64795. }
  64796. this._options = options;
  64797. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64798. this._reusable = reusable || false;
  64799. this._textureType = textureType;
  64800. this._samplers = samplers || [];
  64801. this._samplers.push("textureSampler");
  64802. this._fragmentUrl = fragmentUrl;
  64803. this._vertexUrl = vertexUrl;
  64804. this._parameters = parameters || [];
  64805. this._parameters.push("scale");
  64806. this._indexParameters = indexParameters;
  64807. if (!blockCompilation) {
  64808. this.updateEffect(defines);
  64809. }
  64810. }
  64811. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64812. /**
  64813. * A function that is added to the onActivateObservable
  64814. */
  64815. set: function (callback) {
  64816. if (this._onActivateObserver) {
  64817. this.onActivateObservable.remove(this._onActivateObserver);
  64818. }
  64819. if (callback) {
  64820. this._onActivateObserver = this.onActivateObservable.add(callback);
  64821. }
  64822. },
  64823. enumerable: true,
  64824. configurable: true
  64825. });
  64826. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64827. /**
  64828. * A function that is added to the onSizeChangedObservable
  64829. */
  64830. set: function (callback) {
  64831. if (this._onSizeChangedObserver) {
  64832. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64833. }
  64834. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64835. },
  64836. enumerable: true,
  64837. configurable: true
  64838. });
  64839. Object.defineProperty(PostProcess.prototype, "onApply", {
  64840. /**
  64841. * A function that is added to the onApplyObservable
  64842. */
  64843. set: function (callback) {
  64844. if (this._onApplyObserver) {
  64845. this.onApplyObservable.remove(this._onApplyObserver);
  64846. }
  64847. this._onApplyObserver = this.onApplyObservable.add(callback);
  64848. },
  64849. enumerable: true,
  64850. configurable: true
  64851. });
  64852. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64853. /**
  64854. * A function that is added to the onBeforeRenderObservable
  64855. */
  64856. set: function (callback) {
  64857. if (this._onBeforeRenderObserver) {
  64858. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64859. }
  64860. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64861. },
  64862. enumerable: true,
  64863. configurable: true
  64864. });
  64865. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64866. /**
  64867. * A function that is added to the onAfterRenderObservable
  64868. */
  64869. set: function (callback) {
  64870. if (this._onAfterRenderObserver) {
  64871. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64872. }
  64873. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64874. },
  64875. enumerable: true,
  64876. configurable: true
  64877. });
  64878. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64879. /**
  64880. * 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
  64881. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64882. */
  64883. get: function () {
  64884. return this._textures.data[this._currentRenderTextureInd];
  64885. },
  64886. set: function (value) {
  64887. this._forcedOutputTexture = value;
  64888. },
  64889. enumerable: true,
  64890. configurable: true
  64891. });
  64892. /**
  64893. * Gets the camera which post process is applied to.
  64894. * @returns The camera the post process is applied to.
  64895. */
  64896. PostProcess.prototype.getCamera = function () {
  64897. return this._camera;
  64898. };
  64899. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64900. /**
  64901. * Gets the texel size of the postprocess.
  64902. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64903. */
  64904. get: function () {
  64905. if (this._shareOutputWithPostProcess) {
  64906. return this._shareOutputWithPostProcess.texelSize;
  64907. }
  64908. if (this._forcedOutputTexture) {
  64909. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64910. }
  64911. return this._texelSize;
  64912. },
  64913. enumerable: true,
  64914. configurable: true
  64915. });
  64916. /**
  64917. * Gets the engine which this post process belongs to.
  64918. * @returns The engine the post process was enabled with.
  64919. */
  64920. PostProcess.prototype.getEngine = function () {
  64921. return this._engine;
  64922. };
  64923. /**
  64924. * The effect that is created when initializing the post process.
  64925. * @returns The created effect corrisponding the the postprocess.
  64926. */
  64927. PostProcess.prototype.getEffect = function () {
  64928. return this._effect;
  64929. };
  64930. /**
  64931. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64932. * @param postProcess The post process to share the output with.
  64933. * @returns This post process.
  64934. */
  64935. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64936. this._disposeTextures();
  64937. this._shareOutputWithPostProcess = postProcess;
  64938. return this;
  64939. };
  64940. /**
  64941. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64942. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64943. */
  64944. PostProcess.prototype.useOwnOutput = function () {
  64945. if (this._textures.length == 0) {
  64946. this._textures = new BABYLON.SmartArray(2);
  64947. }
  64948. this._shareOutputWithPostProcess = null;
  64949. };
  64950. /**
  64951. * Updates the effect with the current post process compile time values and recompiles the shader.
  64952. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64953. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64954. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64955. * @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
  64956. * @param onCompiled Called when the shader has been compiled.
  64957. * @param onError Called if there is an error when compiling a shader.
  64958. */
  64959. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64960. if (defines === void 0) { defines = null; }
  64961. if (uniforms === void 0) { uniforms = null; }
  64962. if (samplers === void 0) { samplers = null; }
  64963. 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);
  64964. };
  64965. /**
  64966. * The post process is reusable if it can be used multiple times within one frame.
  64967. * @returns If the post process is reusable
  64968. */
  64969. PostProcess.prototype.isReusable = function () {
  64970. return this._reusable;
  64971. };
  64972. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64973. PostProcess.prototype.markTextureDirty = function () {
  64974. this.width = -1;
  64975. };
  64976. /**
  64977. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64978. * 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.
  64979. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64980. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64981. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64982. * @returns The target texture that was bound to be written to.
  64983. */
  64984. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64985. var _this = this;
  64986. if (sourceTexture === void 0) { sourceTexture = null; }
  64987. camera = camera || this._camera;
  64988. var scene = camera.getScene();
  64989. var engine = scene.getEngine();
  64990. var maxSize = engine.getCaps().maxTextureSize;
  64991. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64992. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64993. // 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
  64994. var webVRCamera = camera.parent;
  64995. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64996. requiredWidth /= 2;
  64997. }
  64998. var desiredWidth = (this._options.width || requiredWidth);
  64999. var desiredHeight = this._options.height || requiredHeight;
  65000. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65001. if (this.adaptScaleToCurrentViewport) {
  65002. var currentViewport = engine.currentViewport;
  65003. if (currentViewport) {
  65004. desiredWidth *= currentViewport.width;
  65005. desiredHeight *= currentViewport.height;
  65006. }
  65007. }
  65008. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65009. if (!this._options.width) {
  65010. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65011. }
  65012. if (!this._options.height) {
  65013. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65014. }
  65015. }
  65016. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65017. if (this._textures.length > 0) {
  65018. for (var i = 0; i < this._textures.length; i++) {
  65019. this._engine._releaseTexture(this._textures.data[i]);
  65020. }
  65021. this._textures.reset();
  65022. }
  65023. this.width = desiredWidth;
  65024. this.height = desiredHeight;
  65025. var textureSize = { width: this.width, height: this.height };
  65026. var textureOptions = {
  65027. generateMipMaps: false,
  65028. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65029. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65030. samplingMode: this.renderTargetSamplingMode,
  65031. type: this._textureType
  65032. };
  65033. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65034. if (this._reusable) {
  65035. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65036. }
  65037. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65038. this.onSizeChangedObservable.notifyObservers(this);
  65039. }
  65040. this._textures.forEach(function (texture) {
  65041. if (texture.samples !== _this.samples) {
  65042. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65043. }
  65044. });
  65045. }
  65046. var target;
  65047. if (this._shareOutputWithPostProcess) {
  65048. target = this._shareOutputWithPostProcess.inputTexture;
  65049. }
  65050. else if (this._forcedOutputTexture) {
  65051. target = this._forcedOutputTexture;
  65052. this.width = this._forcedOutputTexture.width;
  65053. this.height = this._forcedOutputTexture.height;
  65054. }
  65055. else {
  65056. target = this.inputTexture;
  65057. }
  65058. // Bind the input of this post process to be used as the output of the previous post process.
  65059. if (this.enablePixelPerfectMode) {
  65060. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65061. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65062. }
  65063. else {
  65064. this._scaleRatio.copyFromFloats(1, 1);
  65065. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65066. }
  65067. this.onActivateObservable.notifyObservers(camera);
  65068. // Clear
  65069. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65070. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65071. }
  65072. if (this._reusable) {
  65073. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65074. }
  65075. return target;
  65076. };
  65077. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65078. /**
  65079. * If the post process is supported.
  65080. */
  65081. get: function () {
  65082. return this._effect.isSupported;
  65083. },
  65084. enumerable: true,
  65085. configurable: true
  65086. });
  65087. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65088. /**
  65089. * The aspect ratio of the output texture.
  65090. */
  65091. get: function () {
  65092. if (this._shareOutputWithPostProcess) {
  65093. return this._shareOutputWithPostProcess.aspectRatio;
  65094. }
  65095. if (this._forcedOutputTexture) {
  65096. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65097. }
  65098. return this.width / this.height;
  65099. },
  65100. enumerable: true,
  65101. configurable: true
  65102. });
  65103. /**
  65104. * Get a value indicating if the post-process is ready to be used
  65105. * @returns true if the post-process is ready (shader is compiled)
  65106. */
  65107. PostProcess.prototype.isReady = function () {
  65108. return this._effect && this._effect.isReady();
  65109. };
  65110. /**
  65111. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65112. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65113. */
  65114. PostProcess.prototype.apply = function () {
  65115. // Check
  65116. if (!this._effect || !this._effect.isReady())
  65117. return null;
  65118. // States
  65119. this._engine.enableEffect(this._effect);
  65120. this._engine.setState(false);
  65121. this._engine.setDepthBuffer(false);
  65122. this._engine.setDepthWrite(false);
  65123. // Alpha
  65124. this._engine.setAlphaMode(this.alphaMode);
  65125. if (this.alphaConstants) {
  65126. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65127. }
  65128. // Bind the output texture of the preivous post process as the input to this post process.
  65129. var source;
  65130. if (this._shareOutputWithPostProcess) {
  65131. source = this._shareOutputWithPostProcess.inputTexture;
  65132. }
  65133. else if (this._forcedOutputTexture) {
  65134. source = this._forcedOutputTexture;
  65135. }
  65136. else {
  65137. source = this.inputTexture;
  65138. }
  65139. this._effect._bindTexture("textureSampler", source);
  65140. // Parameters
  65141. this._effect.setVector2("scale", this._scaleRatio);
  65142. this.onApplyObservable.notifyObservers(this._effect);
  65143. return this._effect;
  65144. };
  65145. PostProcess.prototype._disposeTextures = function () {
  65146. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65147. return;
  65148. }
  65149. if (this._textures.length > 0) {
  65150. for (var i = 0; i < this._textures.length; i++) {
  65151. this._engine._releaseTexture(this._textures.data[i]);
  65152. }
  65153. }
  65154. this._textures.dispose();
  65155. };
  65156. /**
  65157. * Disposes the post process.
  65158. * @param camera The camera to dispose the post process on.
  65159. */
  65160. PostProcess.prototype.dispose = function (camera) {
  65161. camera = camera || this._camera;
  65162. this._disposeTextures();
  65163. if (this._scene) {
  65164. var index_1 = this._scene.postProcesses.indexOf(this);
  65165. if (index_1 !== -1) {
  65166. this._scene.postProcesses.splice(index_1, 1);
  65167. }
  65168. }
  65169. else {
  65170. var index_2 = this._engine.postProcesses.indexOf(this);
  65171. if (index_2 !== -1) {
  65172. this._engine.postProcesses.splice(index_2, 1);
  65173. }
  65174. }
  65175. if (!camera) {
  65176. return;
  65177. }
  65178. camera.detachPostProcess(this);
  65179. var index = camera._postProcesses.indexOf(this);
  65180. if (index === 0 && camera._postProcesses.length > 0) {
  65181. var firstPostProcess = this._camera._getFirstPostProcess();
  65182. if (firstPostProcess) {
  65183. firstPostProcess.markTextureDirty();
  65184. }
  65185. }
  65186. this.onActivateObservable.clear();
  65187. this.onAfterRenderObservable.clear();
  65188. this.onApplyObservable.clear();
  65189. this.onBeforeRenderObservable.clear();
  65190. this.onSizeChangedObservable.clear();
  65191. };
  65192. return PostProcess;
  65193. }());
  65194. BABYLON.PostProcess = PostProcess;
  65195. })(BABYLON || (BABYLON = {}));
  65196. //# sourceMappingURL=babylon.postProcess.js.map
  65197. var BABYLON;
  65198. (function (BABYLON) {
  65199. var PassPostProcess = /** @class */ (function (_super) {
  65200. __extends(PassPostProcess, _super);
  65201. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65202. if (camera === void 0) { camera = null; }
  65203. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65204. if (blockCompilation === void 0) { blockCompilation = false; }
  65205. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65206. }
  65207. return PassPostProcess;
  65208. }(BABYLON.PostProcess));
  65209. BABYLON.PassPostProcess = PassPostProcess;
  65210. })(BABYLON || (BABYLON = {}));
  65211. //# sourceMappingURL=babylon.passPostProcess.js.map
  65212. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65213. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65214. s = arguments[i];
  65215. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65216. t[p] = s[p];
  65217. }
  65218. return t;
  65219. };
  65220. var BABYLON;
  65221. (function (BABYLON) {
  65222. /**
  65223. * Default implementation IShadowGenerator.
  65224. * This is the main object responsible of generating shadows in the framework.
  65225. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65226. */
  65227. var ShadowGenerator = /** @class */ (function () {
  65228. /**
  65229. * Creates a ShadowGenerator object.
  65230. * A ShadowGenerator is the required tool to use the shadows.
  65231. * Each light casting shadows needs to use its own ShadowGenerator.
  65232. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65233. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65234. * @param light The light object generating the shadows.
  65235. * @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.
  65236. */
  65237. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65238. this._bias = 0.00005;
  65239. this._normalBias = 0;
  65240. this._blurBoxOffset = 1;
  65241. this._blurScale = 2;
  65242. this._blurKernel = 1;
  65243. this._useKernelBlur = false;
  65244. this._filter = ShadowGenerator.FILTER_NONE;
  65245. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65246. this._contactHardeningLightSizeUVRatio = 0.1;
  65247. this._darkness = 0;
  65248. this._transparencyShadow = false;
  65249. /**
  65250. * Controls the extent to which the shadows fade out at the edge of the frustum
  65251. * Used only by directionals and spots
  65252. */
  65253. this.frustumEdgeFalloff = 0;
  65254. /**
  65255. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65256. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65257. * It might on the other hand introduce peter panning.
  65258. */
  65259. this.forceBackFacesOnly = false;
  65260. this._lightDirection = BABYLON.Vector3.Zero();
  65261. this._viewMatrix = BABYLON.Matrix.Zero();
  65262. this._projectionMatrix = BABYLON.Matrix.Zero();
  65263. this._transformMatrix = BABYLON.Matrix.Zero();
  65264. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65265. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65266. this._currentFaceIndex = 0;
  65267. this._currentFaceIndexCache = 0;
  65268. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65269. this._mapSize = mapSize;
  65270. this._light = light;
  65271. this._scene = light.getScene();
  65272. light._shadowGenerator = this;
  65273. // Texture type fallback from float to int if not supported.
  65274. var caps = this._scene.getEngine().getCaps();
  65275. if (!useFullFloatFirst) {
  65276. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65277. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65278. }
  65279. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65280. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65281. }
  65282. else {
  65283. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65284. }
  65285. }
  65286. else {
  65287. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65288. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65289. }
  65290. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65291. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65292. }
  65293. else {
  65294. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65295. }
  65296. }
  65297. this._initializeGenerator();
  65298. this._applyFilterValues();
  65299. }
  65300. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65301. /**
  65302. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65303. */
  65304. get: function () {
  65305. return this._bias;
  65306. },
  65307. /**
  65308. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65309. */
  65310. set: function (bias) {
  65311. this._bias = bias;
  65312. },
  65313. enumerable: true,
  65314. configurable: true
  65315. });
  65316. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65317. /**
  65318. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65319. */
  65320. get: function () {
  65321. return this._normalBias;
  65322. },
  65323. /**
  65324. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65325. */
  65326. set: function (normalBias) {
  65327. this._normalBias = normalBias;
  65328. },
  65329. enumerable: true,
  65330. configurable: true
  65331. });
  65332. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65333. /**
  65334. * Gets the blur box offset: offset applied during the blur pass.
  65335. * Only usefull if useKernelBlur = false
  65336. */
  65337. get: function () {
  65338. return this._blurBoxOffset;
  65339. },
  65340. /**
  65341. * Sets the blur box offset: offset applied during the blur pass.
  65342. * Only usefull if useKernelBlur = false
  65343. */
  65344. set: function (value) {
  65345. if (this._blurBoxOffset === value) {
  65346. return;
  65347. }
  65348. this._blurBoxOffset = value;
  65349. this._disposeBlurPostProcesses();
  65350. },
  65351. enumerable: true,
  65352. configurable: true
  65353. });
  65354. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65355. /**
  65356. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65357. * 2 means half of the size.
  65358. */
  65359. get: function () {
  65360. return this._blurScale;
  65361. },
  65362. /**
  65363. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65364. * 2 means half of the size.
  65365. */
  65366. set: function (value) {
  65367. if (this._blurScale === value) {
  65368. return;
  65369. }
  65370. this._blurScale = value;
  65371. this._disposeBlurPostProcesses();
  65372. },
  65373. enumerable: true,
  65374. configurable: true
  65375. });
  65376. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65377. /**
  65378. * Gets the blur kernel: kernel size of the blur pass.
  65379. * Only usefull if useKernelBlur = true
  65380. */
  65381. get: function () {
  65382. return this._blurKernel;
  65383. },
  65384. /**
  65385. * Sets the blur kernel: kernel size of the blur pass.
  65386. * Only usefull if useKernelBlur = true
  65387. */
  65388. set: function (value) {
  65389. if (this._blurKernel === value) {
  65390. return;
  65391. }
  65392. this._blurKernel = value;
  65393. this._disposeBlurPostProcesses();
  65394. },
  65395. enumerable: true,
  65396. configurable: true
  65397. });
  65398. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65399. /**
  65400. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65401. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65402. */
  65403. get: function () {
  65404. return this._useKernelBlur;
  65405. },
  65406. /**
  65407. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65408. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65409. */
  65410. set: function (value) {
  65411. if (this._useKernelBlur === value) {
  65412. return;
  65413. }
  65414. this._useKernelBlur = value;
  65415. this._disposeBlurPostProcesses();
  65416. },
  65417. enumerable: true,
  65418. configurable: true
  65419. });
  65420. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65421. /**
  65422. * Gets the depth scale used in ESM mode.
  65423. */
  65424. get: function () {
  65425. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65426. },
  65427. /**
  65428. * Sets the depth scale used in ESM mode.
  65429. * This can override the scale stored on the light.
  65430. */
  65431. set: function (value) {
  65432. this._depthScale = value;
  65433. },
  65434. enumerable: true,
  65435. configurable: true
  65436. });
  65437. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65438. /**
  65439. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65440. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65441. */
  65442. get: function () {
  65443. return this._filter;
  65444. },
  65445. /**
  65446. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65447. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65448. */
  65449. set: function (value) {
  65450. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65451. if (this._light.needCube()) {
  65452. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65453. this.useExponentialShadowMap = true;
  65454. return;
  65455. }
  65456. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65457. this.useCloseExponentialShadowMap = true;
  65458. return;
  65459. }
  65460. // PCF on cubemap would also be expensive
  65461. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65462. this.usePoissonSampling = true;
  65463. return;
  65464. }
  65465. }
  65466. // Weblg1 fallback for PCF.
  65467. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65468. if (this._scene.getEngine().webGLVersion === 1) {
  65469. this.usePoissonSampling = true;
  65470. return;
  65471. }
  65472. }
  65473. if (this._filter === value) {
  65474. return;
  65475. }
  65476. this._filter = value;
  65477. this._disposeBlurPostProcesses();
  65478. this._applyFilterValues();
  65479. this._light._markMeshesAsLightDirty();
  65480. },
  65481. enumerable: true,
  65482. configurable: true
  65483. });
  65484. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65485. /**
  65486. * Gets if the current filter is set to Poisson Sampling.
  65487. */
  65488. get: function () {
  65489. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65490. },
  65491. /**
  65492. * Sets the current filter to Poisson Sampling.
  65493. */
  65494. set: function (value) {
  65495. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65496. return;
  65497. }
  65498. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65499. },
  65500. enumerable: true,
  65501. configurable: true
  65502. });
  65503. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65504. /**
  65505. * Gets if the current filter is set to VSM.
  65506. * DEPRECATED. Should use useExponentialShadowMap instead.
  65507. */
  65508. get: function () {
  65509. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65510. return this.useExponentialShadowMap;
  65511. },
  65512. /**
  65513. * Sets the current filter is to VSM.
  65514. * DEPRECATED. Should use useExponentialShadowMap instead.
  65515. */
  65516. set: function (value) {
  65517. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65518. this.useExponentialShadowMap = value;
  65519. },
  65520. enumerable: true,
  65521. configurable: true
  65522. });
  65523. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65524. /**
  65525. * Gets if the current filter is set to blurred VSM.
  65526. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65527. */
  65528. get: function () {
  65529. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65530. return this.useBlurExponentialShadowMap;
  65531. },
  65532. /**
  65533. * Sets the current filter is to blurred VSM.
  65534. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65535. */
  65536. set: function (value) {
  65537. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65538. this.useBlurExponentialShadowMap = value;
  65539. },
  65540. enumerable: true,
  65541. configurable: true
  65542. });
  65543. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65544. /**
  65545. * Gets if the current filter is set to ESM.
  65546. */
  65547. get: function () {
  65548. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65549. },
  65550. /**
  65551. * Sets the current filter is to ESM.
  65552. */
  65553. set: function (value) {
  65554. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65555. return;
  65556. }
  65557. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65558. },
  65559. enumerable: true,
  65560. configurable: true
  65561. });
  65562. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65563. /**
  65564. * Gets if the current filter is set to filtered ESM.
  65565. */
  65566. get: function () {
  65567. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65568. },
  65569. /**
  65570. * Gets if the current filter is set to filtered ESM.
  65571. */
  65572. set: function (value) {
  65573. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65574. return;
  65575. }
  65576. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65577. },
  65578. enumerable: true,
  65579. configurable: true
  65580. });
  65581. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65582. /**
  65583. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65584. * exponential to prevent steep falloff artifacts).
  65585. */
  65586. get: function () {
  65587. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65588. },
  65589. /**
  65590. * Sets the current filter to "close ESM" (using the inverse of the
  65591. * exponential to prevent steep falloff artifacts).
  65592. */
  65593. set: function (value) {
  65594. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65595. return;
  65596. }
  65597. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65598. },
  65599. enumerable: true,
  65600. configurable: true
  65601. });
  65602. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65603. /**
  65604. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65605. * exponential to prevent steep falloff artifacts).
  65606. */
  65607. get: function () {
  65608. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65609. },
  65610. /**
  65611. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65612. * exponential to prevent steep falloff artifacts).
  65613. */
  65614. set: function (value) {
  65615. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65616. return;
  65617. }
  65618. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65619. },
  65620. enumerable: true,
  65621. configurable: true
  65622. });
  65623. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65624. /**
  65625. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65626. */
  65627. get: function () {
  65628. return this.filter === ShadowGenerator.FILTER_PCF;
  65629. },
  65630. /**
  65631. * Sets the current filter to "PCF" (percentage closer filtering).
  65632. */
  65633. set: function (value) {
  65634. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65635. return;
  65636. }
  65637. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65638. },
  65639. enumerable: true,
  65640. configurable: true
  65641. });
  65642. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65643. /**
  65644. * Gets the PCF or PCSS Quality.
  65645. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65646. */
  65647. get: function () {
  65648. return this._filteringQuality;
  65649. },
  65650. /**
  65651. * Sets the PCF or PCSS Quality.
  65652. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65653. */
  65654. set: function (filteringQuality) {
  65655. this._filteringQuality = filteringQuality;
  65656. },
  65657. enumerable: true,
  65658. configurable: true
  65659. });
  65660. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65661. /**
  65662. * Gets if the current filter is set to "PCSS" (contact hardening).
  65663. */
  65664. get: function () {
  65665. return this.filter === ShadowGenerator.FILTER_PCSS;
  65666. },
  65667. /**
  65668. * Sets the current filter to "PCSS" (contact hardening).
  65669. */
  65670. set: function (value) {
  65671. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65672. return;
  65673. }
  65674. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65675. },
  65676. enumerable: true,
  65677. configurable: true
  65678. });
  65679. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65680. /**
  65681. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65682. * Using a ratio helps keeping shape stability independently of the map size.
  65683. *
  65684. * It does not account for the light projection as it was having too much
  65685. * instability during the light setup or during light position changes.
  65686. *
  65687. * Only valid if useContactHardeningShadow is true.
  65688. */
  65689. get: function () {
  65690. return this._contactHardeningLightSizeUVRatio;
  65691. },
  65692. /**
  65693. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65694. * Using a ratio helps keeping shape stability independently of the map size.
  65695. *
  65696. * It does not account for the light projection as it was having too much
  65697. * instability during the light setup or during light position changes.
  65698. *
  65699. * Only valid if useContactHardeningShadow is true.
  65700. */
  65701. set: function (contactHardeningLightSizeUVRatio) {
  65702. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65703. },
  65704. enumerable: true,
  65705. configurable: true
  65706. });
  65707. /**
  65708. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65709. * 0 means strongest and 1 would means no shadow.
  65710. * @returns the darkness.
  65711. */
  65712. ShadowGenerator.prototype.getDarkness = function () {
  65713. return this._darkness;
  65714. };
  65715. /**
  65716. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65717. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65718. * @returns the shadow generator allowing fluent coding.
  65719. */
  65720. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65721. if (darkness >= 1.0)
  65722. this._darkness = 1.0;
  65723. else if (darkness <= 0.0)
  65724. this._darkness = 0.0;
  65725. else
  65726. this._darkness = darkness;
  65727. return this;
  65728. };
  65729. /**
  65730. * Sets the ability to have transparent shadow (boolean).
  65731. * @param transparent True if transparent else False
  65732. * @returns the shadow generator allowing fluent coding
  65733. */
  65734. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65735. this._transparencyShadow = transparent;
  65736. return this;
  65737. };
  65738. /**
  65739. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65740. * @returns The render target texture if present otherwise, null
  65741. */
  65742. ShadowGenerator.prototype.getShadowMap = function () {
  65743. return this._shadowMap;
  65744. };
  65745. /**
  65746. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65747. * @returns The render target texture if the shadow map is present otherwise, null
  65748. */
  65749. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65750. if (this._shadowMap2) {
  65751. return this._shadowMap2;
  65752. }
  65753. return this._shadowMap;
  65754. };
  65755. /**
  65756. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65757. * @param mesh Mesh to add
  65758. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65759. * @returns the Shadow Generator itself
  65760. */
  65761. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65762. if (includeDescendants === void 0) { includeDescendants = true; }
  65763. if (!this._shadowMap) {
  65764. return this;
  65765. }
  65766. if (!this._shadowMap.renderList) {
  65767. this._shadowMap.renderList = [];
  65768. }
  65769. this._shadowMap.renderList.push(mesh);
  65770. if (includeDescendants) {
  65771. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65772. }
  65773. return this;
  65774. var _a;
  65775. };
  65776. /**
  65777. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65778. * @param mesh Mesh to remove
  65779. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65780. * @returns the Shadow Generator itself
  65781. */
  65782. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65783. if (includeDescendants === void 0) { includeDescendants = true; }
  65784. if (!this._shadowMap || !this._shadowMap.renderList) {
  65785. return this;
  65786. }
  65787. var index = this._shadowMap.renderList.indexOf(mesh);
  65788. if (index !== -1) {
  65789. this._shadowMap.renderList.splice(index, 1);
  65790. }
  65791. if (includeDescendants) {
  65792. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65793. var child = _a[_i];
  65794. this.removeShadowCaster(child);
  65795. }
  65796. }
  65797. return this;
  65798. };
  65799. /**
  65800. * Returns the associated light object.
  65801. * @returns the light generating the shadow
  65802. */
  65803. ShadowGenerator.prototype.getLight = function () {
  65804. return this._light;
  65805. };
  65806. ShadowGenerator.prototype._initializeGenerator = function () {
  65807. this._light._markMeshesAsLightDirty();
  65808. this._initializeShadowMap();
  65809. };
  65810. ShadowGenerator.prototype._initializeShadowMap = function () {
  65811. var _this = this;
  65812. // Render target
  65813. var engine = this._scene.getEngine();
  65814. if (engine.webGLVersion > 1) {
  65815. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65816. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65817. }
  65818. else {
  65819. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65820. }
  65821. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65822. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65823. this._shadowMap.anisotropicFilteringLevel = 1;
  65824. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65825. this._shadowMap.renderParticles = false;
  65826. this._shadowMap.ignoreCameraViewport = true;
  65827. // Record Face Index before render.
  65828. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65829. _this._currentFaceIndex = faceIndex;
  65830. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65831. engine.setColorWrite(false);
  65832. }
  65833. });
  65834. // Custom render function.
  65835. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65836. // Blur if required afer render.
  65837. this._shadowMap.onAfterUnbindObservable.add(function () {
  65838. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65839. engine.setColorWrite(true);
  65840. }
  65841. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65842. return;
  65843. }
  65844. var shadowMap = _this.getShadowMapForRendering();
  65845. if (shadowMap) {
  65846. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65847. }
  65848. });
  65849. // Clear according to the chosen filter.
  65850. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65851. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65852. this._shadowMap.onClearObservable.add(function (engine) {
  65853. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65854. engine.clear(clearOne, false, true, false);
  65855. }
  65856. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65857. engine.clear(clearZero, true, true, false);
  65858. }
  65859. else {
  65860. engine.clear(clearOne, true, true, false);
  65861. }
  65862. });
  65863. };
  65864. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65865. var _this = this;
  65866. var engine = this._scene.getEngine();
  65867. var targetSize = this._mapSize / this.blurScale;
  65868. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65869. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65870. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65871. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65872. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65873. }
  65874. if (this.useKernelBlur) {
  65875. 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);
  65876. this._kernelBlurXPostprocess.width = targetSize;
  65877. this._kernelBlurXPostprocess.height = targetSize;
  65878. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65879. effect.setTexture("textureSampler", _this._shadowMap);
  65880. });
  65881. 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);
  65882. this._kernelBlurXPostprocess.autoClear = false;
  65883. this._kernelBlurYPostprocess.autoClear = false;
  65884. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65885. this._kernelBlurXPostprocess.packedFloat = true;
  65886. this._kernelBlurYPostprocess.packedFloat = true;
  65887. }
  65888. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65889. }
  65890. else {
  65891. 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);
  65892. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65893. effect.setFloat2("screenSize", targetSize, targetSize);
  65894. effect.setTexture("textureSampler", _this._shadowMap);
  65895. });
  65896. this._boxBlurPostprocess.autoClear = false;
  65897. this._blurPostProcesses = [this._boxBlurPostprocess];
  65898. }
  65899. };
  65900. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65901. var index;
  65902. var engine = this._scene.getEngine();
  65903. if (depthOnlySubMeshes.length) {
  65904. engine.setColorWrite(false);
  65905. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65906. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65907. }
  65908. engine.setColorWrite(true);
  65909. }
  65910. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65911. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65912. }
  65913. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65914. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65915. }
  65916. if (this._transparencyShadow) {
  65917. for (index = 0; index < transparentSubMeshes.length; index++) {
  65918. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65919. }
  65920. }
  65921. };
  65922. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65923. var _this = this;
  65924. var mesh = subMesh.getRenderingMesh();
  65925. var scene = this._scene;
  65926. var engine = scene.getEngine();
  65927. var material = subMesh.getMaterial();
  65928. if (!material) {
  65929. return;
  65930. }
  65931. // Culling
  65932. engine.setState(material.backFaceCulling);
  65933. // Managing instances
  65934. var batch = mesh._getInstancesRenderList(subMesh._id);
  65935. if (batch.mustReturn) {
  65936. return;
  65937. }
  65938. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65939. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65940. engine.enableEffect(this._effect);
  65941. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65942. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65943. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65944. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65945. this._effect.setVector3("lightData", this._cachedDirection);
  65946. }
  65947. else {
  65948. this._effect.setVector3("lightData", this._cachedPosition);
  65949. }
  65950. if (scene.activeCamera) {
  65951. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65952. }
  65953. // Alpha test
  65954. if (material && material.needAlphaTesting()) {
  65955. var alphaTexture = material.getAlphaTestTexture();
  65956. if (alphaTexture) {
  65957. this._effect.setTexture("diffuseSampler", alphaTexture);
  65958. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65959. }
  65960. }
  65961. // Bones
  65962. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65963. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65964. }
  65965. // Morph targets
  65966. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65967. if (this.forceBackFacesOnly) {
  65968. engine.setState(true, 0, false, true);
  65969. }
  65970. // Draw
  65971. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65972. if (this.forceBackFacesOnly) {
  65973. engine.setState(true, 0, false, false);
  65974. }
  65975. }
  65976. else {
  65977. // Need to reset refresh rate of the shadowMap
  65978. if (this._shadowMap) {
  65979. this._shadowMap.resetRefreshCounter();
  65980. }
  65981. }
  65982. };
  65983. ShadowGenerator.prototype._applyFilterValues = function () {
  65984. if (!this._shadowMap) {
  65985. return;
  65986. }
  65987. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65988. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65989. }
  65990. else {
  65991. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65992. }
  65993. };
  65994. /**
  65995. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65996. * @param onCompiled Callback triggered at the and of the effects compilation
  65997. * @param options Sets of optional options forcing the compilation with different modes
  65998. */
  65999. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66000. var _this = this;
  66001. var localOptions = __assign({ useInstances: false }, options);
  66002. var shadowMap = this.getShadowMap();
  66003. if (!shadowMap) {
  66004. if (onCompiled) {
  66005. onCompiled(this);
  66006. }
  66007. return;
  66008. }
  66009. var renderList = shadowMap.renderList;
  66010. if (!renderList) {
  66011. if (onCompiled) {
  66012. onCompiled(this);
  66013. }
  66014. return;
  66015. }
  66016. var subMeshes = new Array();
  66017. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66018. var mesh = renderList_1[_i];
  66019. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66020. }
  66021. if (subMeshes.length === 0) {
  66022. if (onCompiled) {
  66023. onCompiled(this);
  66024. }
  66025. return;
  66026. }
  66027. var currentIndex = 0;
  66028. var checkReady = function () {
  66029. if (!_this._scene || !_this._scene.getEngine()) {
  66030. return;
  66031. }
  66032. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66033. currentIndex++;
  66034. if (currentIndex >= subMeshes.length) {
  66035. if (onCompiled) {
  66036. onCompiled(_this);
  66037. }
  66038. return;
  66039. }
  66040. }
  66041. setTimeout(checkReady, 16);
  66042. };
  66043. checkReady();
  66044. };
  66045. /**
  66046. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66047. * @param options Sets of optional options forcing the compilation with different modes
  66048. * @returns A promise that resolves when the compilation completes
  66049. */
  66050. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66051. var _this = this;
  66052. return new Promise(function (resolve) {
  66053. _this.forceCompilation(function () {
  66054. resolve();
  66055. }, options);
  66056. });
  66057. };
  66058. /**
  66059. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66060. * @param subMesh The submesh we want to render in the shadow map
  66061. * @param useInstances Defines wether will draw in the map using instances
  66062. * @returns true if ready otherwise, false
  66063. */
  66064. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66065. var defines = [];
  66066. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66067. defines.push("#define FLOAT");
  66068. }
  66069. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66070. defines.push("#define ESM");
  66071. }
  66072. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66073. defines.push("#define DEPTHTEXTURE");
  66074. }
  66075. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66076. var mesh = subMesh.getMesh();
  66077. var material = subMesh.getMaterial();
  66078. // Normal bias.
  66079. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66080. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66081. defines.push("#define NORMAL");
  66082. if (mesh.nonUniformScaling) {
  66083. defines.push("#define NONUNIFORMSCALING");
  66084. }
  66085. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66086. defines.push("#define DIRECTIONINLIGHTDATA");
  66087. }
  66088. }
  66089. // Alpha test
  66090. if (material && material.needAlphaTesting()) {
  66091. var alphaTexture = material.getAlphaTestTexture();
  66092. if (alphaTexture) {
  66093. defines.push("#define ALPHATEST");
  66094. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66095. attribs.push(BABYLON.VertexBuffer.UVKind);
  66096. defines.push("#define UV1");
  66097. }
  66098. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66099. if (alphaTexture.coordinatesIndex === 1) {
  66100. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66101. defines.push("#define UV2");
  66102. }
  66103. }
  66104. }
  66105. }
  66106. // Bones
  66107. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66108. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66109. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66110. if (mesh.numBoneInfluencers > 4) {
  66111. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66112. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66113. }
  66114. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66115. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66116. }
  66117. else {
  66118. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66119. }
  66120. // Morph targets
  66121. var manager = mesh.morphTargetManager;
  66122. var morphInfluencers = 0;
  66123. if (manager) {
  66124. if (manager.numInfluencers > 0) {
  66125. defines.push("#define MORPHTARGETS");
  66126. morphInfluencers = manager.numInfluencers;
  66127. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66128. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66129. }
  66130. }
  66131. // Instances
  66132. if (useInstances) {
  66133. defines.push("#define INSTANCES");
  66134. attribs.push("world0");
  66135. attribs.push("world1");
  66136. attribs.push("world2");
  66137. attribs.push("world3");
  66138. }
  66139. // Get correct effect
  66140. var join = defines.join("\n");
  66141. if (this._cachedDefines !== join) {
  66142. this._cachedDefines = join;
  66143. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66144. }
  66145. if (!this._effect.isReady()) {
  66146. return false;
  66147. }
  66148. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66149. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66150. this._initializeBlurRTTAndPostProcesses();
  66151. }
  66152. }
  66153. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66154. return false;
  66155. }
  66156. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66157. return false;
  66158. }
  66159. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66160. return false;
  66161. }
  66162. return true;
  66163. };
  66164. /**
  66165. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66166. * @param defines Defines of the material we want to update
  66167. * @param lightIndex Index of the light in the enabled light list of the material
  66168. */
  66169. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66170. var scene = this._scene;
  66171. var light = this._light;
  66172. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66173. return;
  66174. }
  66175. defines["SHADOW" + lightIndex] = true;
  66176. if (this.useContactHardeningShadow) {
  66177. defines["SHADOWPCSS" + lightIndex] = true;
  66178. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66179. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66180. }
  66181. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66182. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66183. }
  66184. // else default to high.
  66185. }
  66186. if (this.usePercentageCloserFiltering) {
  66187. defines["SHADOWPCF" + lightIndex] = true;
  66188. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66189. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66190. }
  66191. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66192. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66193. }
  66194. // else default to high.
  66195. }
  66196. else if (this.usePoissonSampling) {
  66197. defines["SHADOWPOISSON" + lightIndex] = true;
  66198. }
  66199. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66200. defines["SHADOWESM" + lightIndex] = true;
  66201. }
  66202. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66203. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66204. }
  66205. if (light.needCube()) {
  66206. defines["SHADOWCUBE" + lightIndex] = true;
  66207. }
  66208. };
  66209. /**
  66210. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66211. * defined in the generator but impacting the effect).
  66212. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66213. * @param effect The effect we are binfing the information for
  66214. */
  66215. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66216. var light = this._light;
  66217. var scene = this._scene;
  66218. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66219. return;
  66220. }
  66221. var camera = scene.activeCamera;
  66222. if (!camera) {
  66223. return;
  66224. }
  66225. var shadowMap = this.getShadowMap();
  66226. if (!shadowMap) {
  66227. return;
  66228. }
  66229. if (!light.needCube()) {
  66230. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66231. }
  66232. // Only PCF uses depth stencil texture.
  66233. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66234. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66235. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66236. }
  66237. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66238. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66239. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66240. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66241. }
  66242. else {
  66243. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66244. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66245. }
  66246. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66247. };
  66248. /**
  66249. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66250. * (eq to shadow prjection matrix * light transform matrix)
  66251. * @returns The transform matrix used to create the shadow map
  66252. */
  66253. ShadowGenerator.prototype.getTransformMatrix = function () {
  66254. var scene = this._scene;
  66255. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66256. return this._transformMatrix;
  66257. }
  66258. this._currentRenderID = scene.getRenderId();
  66259. this._currentFaceIndexCache = this._currentFaceIndex;
  66260. var lightPosition = this._light.position;
  66261. if (this._light.computeTransformedInformation()) {
  66262. lightPosition = this._light.transformedPosition;
  66263. }
  66264. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66265. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66266. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66267. }
  66268. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66269. this._cachedPosition.copyFrom(lightPosition);
  66270. this._cachedDirection.copyFrom(this._lightDirection);
  66271. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66272. var shadowMap = this.getShadowMap();
  66273. if (shadowMap) {
  66274. var renderList = shadowMap.renderList;
  66275. if (renderList) {
  66276. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66277. }
  66278. }
  66279. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66280. }
  66281. return this._transformMatrix;
  66282. };
  66283. /**
  66284. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66285. * Cube and 2D textures for instance.
  66286. */
  66287. ShadowGenerator.prototype.recreateShadowMap = function () {
  66288. var shadowMap = this._shadowMap;
  66289. if (!shadowMap) {
  66290. return;
  66291. }
  66292. // Track render list.
  66293. var renderList = shadowMap.renderList;
  66294. // Clean up existing data.
  66295. this._disposeRTTandPostProcesses();
  66296. // Reinitializes.
  66297. this._initializeGenerator();
  66298. // Reaffect the filter to ensure a correct fallback if necessary.
  66299. this.filter = this.filter;
  66300. // Reaffect the filter.
  66301. this._applyFilterValues();
  66302. // Reaffect Render List.
  66303. this._shadowMap.renderList = renderList;
  66304. };
  66305. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66306. if (this._shadowMap2) {
  66307. this._shadowMap2.dispose();
  66308. this._shadowMap2 = null;
  66309. }
  66310. if (this._boxBlurPostprocess) {
  66311. this._boxBlurPostprocess.dispose();
  66312. this._boxBlurPostprocess = null;
  66313. }
  66314. if (this._kernelBlurXPostprocess) {
  66315. this._kernelBlurXPostprocess.dispose();
  66316. this._kernelBlurXPostprocess = null;
  66317. }
  66318. if (this._kernelBlurYPostprocess) {
  66319. this._kernelBlurYPostprocess.dispose();
  66320. this._kernelBlurYPostprocess = null;
  66321. }
  66322. this._blurPostProcesses = [];
  66323. };
  66324. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66325. if (this._shadowMap) {
  66326. this._shadowMap.dispose();
  66327. this._shadowMap = null;
  66328. }
  66329. this._disposeBlurPostProcesses();
  66330. };
  66331. /**
  66332. * Disposes the ShadowGenerator.
  66333. * Returns nothing.
  66334. */
  66335. ShadowGenerator.prototype.dispose = function () {
  66336. this._disposeRTTandPostProcesses();
  66337. if (this._light) {
  66338. this._light._shadowGenerator = null;
  66339. this._light._markMeshesAsLightDirty();
  66340. }
  66341. };
  66342. /**
  66343. * Serializes the shadow generator setup to a json object.
  66344. * @returns The serialized JSON object
  66345. */
  66346. ShadowGenerator.prototype.serialize = function () {
  66347. var serializationObject = {};
  66348. var shadowMap = this.getShadowMap();
  66349. if (!shadowMap) {
  66350. return serializationObject;
  66351. }
  66352. serializationObject.lightId = this._light.id;
  66353. serializationObject.mapSize = shadowMap.getRenderSize();
  66354. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66355. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66356. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66357. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66358. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66359. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66360. serializationObject.depthScale = this.depthScale;
  66361. serializationObject.darkness = this.getDarkness();
  66362. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66363. serializationObject.blurKernel = this.blurKernel;
  66364. serializationObject.blurScale = this.blurScale;
  66365. serializationObject.useKernelBlur = this.useKernelBlur;
  66366. serializationObject.transparencyShadow = this._transparencyShadow;
  66367. serializationObject.bias = this.bias;
  66368. serializationObject.normalBias = this.normalBias;
  66369. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66370. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66371. serializationObject.filteringQuality = this.filteringQuality;
  66372. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66373. serializationObject.renderList = [];
  66374. if (shadowMap.renderList) {
  66375. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66376. var mesh = shadowMap.renderList[meshIndex];
  66377. serializationObject.renderList.push(mesh.id);
  66378. }
  66379. }
  66380. return serializationObject;
  66381. };
  66382. /**
  66383. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66384. * @param parsedShadowGenerator The JSON object to parse
  66385. * @param scene The scene to create the shadow map for
  66386. * @returns The parsed shadow generator
  66387. */
  66388. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66389. //casting to point light, as light is missing the position attr and typescript complains.
  66390. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66391. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66392. var shadowMap = shadowGenerator.getShadowMap();
  66393. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66394. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66395. meshes.forEach(function (mesh) {
  66396. if (!shadowMap) {
  66397. return;
  66398. }
  66399. if (!shadowMap.renderList) {
  66400. shadowMap.renderList = [];
  66401. }
  66402. shadowMap.renderList.push(mesh);
  66403. });
  66404. }
  66405. if (parsedShadowGenerator.usePoissonSampling) {
  66406. shadowGenerator.usePoissonSampling = true;
  66407. }
  66408. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66409. shadowGenerator.useExponentialShadowMap = true;
  66410. }
  66411. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66412. shadowGenerator.useBlurExponentialShadowMap = true;
  66413. }
  66414. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66415. shadowGenerator.useCloseExponentialShadowMap = true;
  66416. }
  66417. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66418. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66419. }
  66420. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66421. shadowGenerator.usePercentageCloserFiltering = true;
  66422. }
  66423. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66424. shadowGenerator.useContactHardeningShadow = true;
  66425. }
  66426. if (parsedShadowGenerator.filteringQuality) {
  66427. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66428. }
  66429. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66430. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66431. }
  66432. // Backward compat
  66433. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66434. shadowGenerator.useExponentialShadowMap = true;
  66435. }
  66436. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66437. shadowGenerator.useBlurExponentialShadowMap = true;
  66438. }
  66439. if (parsedShadowGenerator.depthScale) {
  66440. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66441. }
  66442. if (parsedShadowGenerator.blurScale) {
  66443. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66444. }
  66445. if (parsedShadowGenerator.blurBoxOffset) {
  66446. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66447. }
  66448. if (parsedShadowGenerator.useKernelBlur) {
  66449. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66450. }
  66451. if (parsedShadowGenerator.blurKernel) {
  66452. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66453. }
  66454. if (parsedShadowGenerator.bias !== undefined) {
  66455. shadowGenerator.bias = parsedShadowGenerator.bias;
  66456. }
  66457. if (parsedShadowGenerator.normalBias !== undefined) {
  66458. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66459. }
  66460. if (parsedShadowGenerator.darkness) {
  66461. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66462. }
  66463. if (parsedShadowGenerator.transparencyShadow) {
  66464. shadowGenerator.setTransparencyShadow(true);
  66465. }
  66466. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66467. return shadowGenerator;
  66468. };
  66469. /**
  66470. * Shadow generator mode None: no filtering applied.
  66471. */
  66472. ShadowGenerator.FILTER_NONE = 0;
  66473. /**
  66474. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66475. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66476. */
  66477. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66478. /**
  66479. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66480. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66481. */
  66482. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66483. /**
  66484. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66485. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66486. */
  66487. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66488. /**
  66489. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66490. * edge artifacts on steep falloff.
  66491. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66492. */
  66493. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66494. /**
  66495. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66496. * edge artifacts on steep falloff.
  66497. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66498. */
  66499. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66500. /**
  66501. * Shadow generator mode PCF: Percentage Closer Filtering
  66502. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66503. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66504. */
  66505. ShadowGenerator.FILTER_PCF = 6;
  66506. /**
  66507. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66508. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66509. * Contact Hardening
  66510. */
  66511. ShadowGenerator.FILTER_PCSS = 7;
  66512. /**
  66513. * Reserved for PCF and PCSS
  66514. * Highest Quality.
  66515. *
  66516. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66517. *
  66518. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66519. */
  66520. ShadowGenerator.QUALITY_HIGH = 0;
  66521. /**
  66522. * Reserved for PCF and PCSS
  66523. * Good tradeoff for quality/perf cross devices
  66524. *
  66525. * Execute PCF on a 3*3 kernel.
  66526. *
  66527. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66528. */
  66529. ShadowGenerator.QUALITY_MEDIUM = 1;
  66530. /**
  66531. * Reserved for PCF and PCSS
  66532. * The lowest quality but the fastest.
  66533. *
  66534. * Execute PCF on a 1*1 kernel.
  66535. *
  66536. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66537. */
  66538. ShadowGenerator.QUALITY_LOW = 2;
  66539. return ShadowGenerator;
  66540. }());
  66541. BABYLON.ShadowGenerator = ShadowGenerator;
  66542. })(BABYLON || (BABYLON = {}));
  66543. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66544. var BABYLON;
  66545. (function (BABYLON) {
  66546. var DefaultLoadingScreen = /** @class */ (function () {
  66547. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66548. if (_loadingText === void 0) { _loadingText = ""; }
  66549. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66550. var _this = this;
  66551. this._renderingCanvas = _renderingCanvas;
  66552. this._loadingText = _loadingText;
  66553. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66554. // Resize
  66555. this._resizeLoadingUI = function () {
  66556. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66557. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66558. if (!_this._loadingDiv) {
  66559. return;
  66560. }
  66561. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66562. _this._loadingDiv.style.left = canvasRect.left + "px";
  66563. _this._loadingDiv.style.top = canvasRect.top + "px";
  66564. _this._loadingDiv.style.width = canvasRect.width + "px";
  66565. _this._loadingDiv.style.height = canvasRect.height + "px";
  66566. };
  66567. }
  66568. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66569. if (this._loadingDiv) {
  66570. // Do not add a loading screen if there is already one
  66571. return;
  66572. }
  66573. this._loadingDiv = document.createElement("div");
  66574. this._loadingDiv.id = "babylonjsLoadingDiv";
  66575. this._loadingDiv.style.opacity = "0";
  66576. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66577. this._loadingDiv.style.pointerEvents = "none";
  66578. // Loading text
  66579. this._loadingTextDiv = document.createElement("div");
  66580. this._loadingTextDiv.style.position = "absolute";
  66581. this._loadingTextDiv.style.left = "0";
  66582. this._loadingTextDiv.style.top = "50%";
  66583. this._loadingTextDiv.style.marginTop = "80px";
  66584. this._loadingTextDiv.style.width = "100%";
  66585. this._loadingTextDiv.style.height = "20px";
  66586. this._loadingTextDiv.style.fontFamily = "Arial";
  66587. this._loadingTextDiv.style.fontSize = "14px";
  66588. this._loadingTextDiv.style.color = "white";
  66589. this._loadingTextDiv.style.textAlign = "center";
  66590. this._loadingTextDiv.innerHTML = "Loading";
  66591. this._loadingDiv.appendChild(this._loadingTextDiv);
  66592. //set the predefined text
  66593. this._loadingTextDiv.innerHTML = this._loadingText;
  66594. // Generating keyframes
  66595. var style = document.createElement('style');
  66596. style.type = 'text/css';
  66597. 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 }";
  66598. style.innerHTML = keyFrames;
  66599. document.getElementsByTagName('head')[0].appendChild(style);
  66600. // Loading img
  66601. var imgBack = new Image();
  66602. 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";
  66603. imgBack.style.position = "absolute";
  66604. imgBack.style.left = "50%";
  66605. imgBack.style.top = "50%";
  66606. imgBack.style.marginLeft = "-60px";
  66607. imgBack.style.marginTop = "-60px";
  66608. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66609. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66610. imgBack.style.transformOrigin = "50% 50%";
  66611. imgBack.style.webkitTransformOrigin = "50% 50%";
  66612. this._loadingDiv.appendChild(imgBack);
  66613. this._resizeLoadingUI();
  66614. window.addEventListener("resize", this._resizeLoadingUI);
  66615. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66616. document.body.appendChild(this._loadingDiv);
  66617. this._loadingDiv.style.opacity = "1";
  66618. };
  66619. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66620. var _this = this;
  66621. if (!this._loadingDiv) {
  66622. return;
  66623. }
  66624. var onTransitionEnd = function () {
  66625. if (!_this._loadingDiv) {
  66626. return;
  66627. }
  66628. document.body.removeChild(_this._loadingDiv);
  66629. window.removeEventListener("resize", _this._resizeLoadingUI);
  66630. _this._loadingDiv = null;
  66631. };
  66632. this._loadingDiv.style.opacity = "0";
  66633. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66634. };
  66635. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66636. set: function (text) {
  66637. this._loadingText = text;
  66638. if (this._loadingTextDiv) {
  66639. this._loadingTextDiv.innerHTML = this._loadingText;
  66640. }
  66641. },
  66642. enumerable: true,
  66643. configurable: true
  66644. });
  66645. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66646. get: function () {
  66647. return this._loadingDivBackgroundColor;
  66648. },
  66649. set: function (color) {
  66650. this._loadingDivBackgroundColor = color;
  66651. if (!this._loadingDiv) {
  66652. return;
  66653. }
  66654. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66655. },
  66656. enumerable: true,
  66657. configurable: true
  66658. });
  66659. return DefaultLoadingScreen;
  66660. }());
  66661. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66662. })(BABYLON || (BABYLON = {}));
  66663. //# sourceMappingURL=babylon.loadingScreen.js.map
  66664. var BABYLON;
  66665. (function (BABYLON) {
  66666. var SceneLoaderProgressEvent = /** @class */ (function () {
  66667. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66668. this.lengthComputable = lengthComputable;
  66669. this.loaded = loaded;
  66670. this.total = total;
  66671. }
  66672. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66673. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66674. };
  66675. return SceneLoaderProgressEvent;
  66676. }());
  66677. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66678. var SceneLoader = /** @class */ (function () {
  66679. function SceneLoader() {
  66680. }
  66681. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66682. get: function () {
  66683. return 0;
  66684. },
  66685. enumerable: true,
  66686. configurable: true
  66687. });
  66688. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66689. get: function () {
  66690. return 1;
  66691. },
  66692. enumerable: true,
  66693. configurable: true
  66694. });
  66695. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66696. get: function () {
  66697. return 2;
  66698. },
  66699. enumerable: true,
  66700. configurable: true
  66701. });
  66702. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66703. get: function () {
  66704. return 3;
  66705. },
  66706. enumerable: true,
  66707. configurable: true
  66708. });
  66709. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66710. get: function () {
  66711. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66712. },
  66713. set: function (value) {
  66714. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66715. },
  66716. enumerable: true,
  66717. configurable: true
  66718. });
  66719. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66720. get: function () {
  66721. return SceneLoader._ShowLoadingScreen;
  66722. },
  66723. set: function (value) {
  66724. SceneLoader._ShowLoadingScreen = value;
  66725. },
  66726. enumerable: true,
  66727. configurable: true
  66728. });
  66729. Object.defineProperty(SceneLoader, "loggingLevel", {
  66730. get: function () {
  66731. return SceneLoader._loggingLevel;
  66732. },
  66733. set: function (value) {
  66734. SceneLoader._loggingLevel = value;
  66735. },
  66736. enumerable: true,
  66737. configurable: true
  66738. });
  66739. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66740. get: function () {
  66741. return SceneLoader._CleanBoneMatrixWeights;
  66742. },
  66743. set: function (value) {
  66744. SceneLoader._CleanBoneMatrixWeights = value;
  66745. },
  66746. enumerable: true,
  66747. configurable: true
  66748. });
  66749. SceneLoader._getDefaultPlugin = function () {
  66750. return SceneLoader._registeredPlugins[".babylon"];
  66751. };
  66752. SceneLoader._getPluginForExtension = function (extension) {
  66753. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66754. if (registeredPlugin) {
  66755. return registeredPlugin;
  66756. }
  66757. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66758. return SceneLoader._getDefaultPlugin();
  66759. };
  66760. SceneLoader._getPluginForDirectLoad = function (data) {
  66761. for (var extension in SceneLoader._registeredPlugins) {
  66762. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66763. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66764. return SceneLoader._registeredPlugins[extension];
  66765. }
  66766. }
  66767. return SceneLoader._getDefaultPlugin();
  66768. };
  66769. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66770. if (sceneFilename.name) {
  66771. sceneFilename = sceneFilename.name;
  66772. }
  66773. var queryStringPosition = sceneFilename.indexOf("?");
  66774. if (queryStringPosition !== -1) {
  66775. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66776. }
  66777. var dotPosition = sceneFilename.lastIndexOf(".");
  66778. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66779. return SceneLoader._getPluginForExtension(extension);
  66780. };
  66781. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66782. SceneLoader._getDirectLoad = function (sceneFilename) {
  66783. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66784. return sceneFilename.substr(5);
  66785. }
  66786. return null;
  66787. };
  66788. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66789. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66790. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66791. var plugin;
  66792. if (registeredPlugin.plugin.createPlugin) {
  66793. plugin = registeredPlugin.plugin.createPlugin();
  66794. }
  66795. else {
  66796. plugin = registeredPlugin.plugin;
  66797. }
  66798. var useArrayBuffer = registeredPlugin.isBinary;
  66799. var database;
  66800. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66801. var dataCallback = function (data, responseURL) {
  66802. if (scene.isDisposed) {
  66803. onError("Scene has been disposed");
  66804. return;
  66805. }
  66806. scene.database = database;
  66807. onSuccess(plugin, data, responseURL);
  66808. };
  66809. var request = null;
  66810. var pluginDisposed = false;
  66811. var onDisposeObservable = plugin.onDisposeObservable;
  66812. if (onDisposeObservable) {
  66813. onDisposeObservable.add(function () {
  66814. pluginDisposed = true;
  66815. if (request) {
  66816. request.abort();
  66817. request = null;
  66818. }
  66819. onDispose();
  66820. });
  66821. }
  66822. var manifestChecked = function () {
  66823. if (pluginDisposed) {
  66824. return;
  66825. }
  66826. var url = rootUrl + sceneFilename;
  66827. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66828. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66829. } : undefined, database, useArrayBuffer, function (request, exception) {
  66830. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66831. });
  66832. };
  66833. if (directLoad) {
  66834. dataCallback(directLoad);
  66835. return plugin;
  66836. }
  66837. if (rootUrl.indexOf("file:") === -1) {
  66838. var engine = scene.getEngine();
  66839. var canUseOfflineSupport = engine.enableOfflineSupport;
  66840. if (canUseOfflineSupport) {
  66841. // Also check for exceptions
  66842. var exceptionFound = false;
  66843. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66844. var regex = _a[_i];
  66845. if (regex.test(rootUrl + sceneFilename)) {
  66846. exceptionFound = true;
  66847. break;
  66848. }
  66849. }
  66850. canUseOfflineSupport = !exceptionFound;
  66851. }
  66852. if (canUseOfflineSupport) {
  66853. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66854. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66855. }
  66856. else {
  66857. manifestChecked();
  66858. }
  66859. }
  66860. // Loading file from disk via input file or drag'n'drop
  66861. else {
  66862. var fileOrString = sceneFilename;
  66863. if (fileOrString.name) { // File
  66864. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66865. }
  66866. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66867. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66868. }
  66869. else {
  66870. onError("Unable to find file named " + sceneFilename);
  66871. }
  66872. }
  66873. return plugin;
  66874. };
  66875. // Public functions
  66876. SceneLoader.GetPluginForExtension = function (extension) {
  66877. return SceneLoader._getPluginForExtension(extension).plugin;
  66878. };
  66879. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66880. return !!SceneLoader._registeredPlugins[extension];
  66881. };
  66882. SceneLoader.RegisterPlugin = function (plugin) {
  66883. if (typeof plugin.extensions === "string") {
  66884. var extension = plugin.extensions;
  66885. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66886. plugin: plugin,
  66887. isBinary: false
  66888. };
  66889. }
  66890. else {
  66891. var extensions = plugin.extensions;
  66892. Object.keys(extensions).forEach(function (extension) {
  66893. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66894. plugin: plugin,
  66895. isBinary: extensions[extension].isBinary
  66896. };
  66897. });
  66898. }
  66899. };
  66900. /**
  66901. * Import meshes into a scene
  66902. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66903. * @param rootUrl a string that defines the root url for scene and resources
  66904. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66905. * @param scene the instance of BABYLON.Scene to append to
  66906. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66907. * @param onProgress a callback with a progress event for each file being loaded
  66908. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66909. * @param pluginExtension the extension used to determine the plugin
  66910. * @returns The loaded plugin
  66911. */
  66912. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66913. if (onSuccess === void 0) { onSuccess = null; }
  66914. if (onProgress === void 0) { onProgress = null; }
  66915. if (onError === void 0) { onError = null; }
  66916. if (pluginExtension === void 0) { pluginExtension = null; }
  66917. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66918. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66919. return null;
  66920. }
  66921. var loadingToken = {};
  66922. scene._addPendingData(loadingToken);
  66923. var disposeHandler = function () {
  66924. scene._removePendingData(loadingToken);
  66925. };
  66926. var errorHandler = function (message, exception) {
  66927. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66928. if (onError) {
  66929. onError(scene, errorMessage, exception);
  66930. }
  66931. else {
  66932. BABYLON.Tools.Error(errorMessage);
  66933. // should the exception be thrown?
  66934. }
  66935. disposeHandler();
  66936. };
  66937. var progressHandler = onProgress ? function (event) {
  66938. try {
  66939. onProgress(event);
  66940. }
  66941. catch (e) {
  66942. errorHandler("Error in onProgress callback", e);
  66943. }
  66944. } : undefined;
  66945. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66946. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66947. if (onSuccess) {
  66948. try {
  66949. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66950. }
  66951. catch (e) {
  66952. errorHandler("Error in onSuccess callback", e);
  66953. }
  66954. }
  66955. scene._removePendingData(loadingToken);
  66956. };
  66957. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66958. if (plugin.rewriteRootURL) {
  66959. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66960. }
  66961. if (sceneFilename === "") {
  66962. if (sceneFilename === "") {
  66963. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66964. }
  66965. }
  66966. if (plugin.importMesh) {
  66967. var syncedPlugin = plugin;
  66968. var meshes = new Array();
  66969. var particleSystems = new Array();
  66970. var skeletons = new Array();
  66971. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66972. return;
  66973. }
  66974. scene.loadingPluginName = plugin.name;
  66975. successHandler(meshes, particleSystems, skeletons, []);
  66976. }
  66977. else {
  66978. var asyncedPlugin = plugin;
  66979. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66980. scene.loadingPluginName = plugin.name;
  66981. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66982. }).catch(function (error) {
  66983. errorHandler(error.message, error);
  66984. });
  66985. }
  66986. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66987. };
  66988. /**
  66989. * Import meshes into a scene
  66990. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66991. * @param rootUrl a string that defines the root url for scene and resources
  66992. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66993. * @param scene the instance of BABYLON.Scene to append to
  66994. * @param onProgress a callback with a progress event for each file being loaded
  66995. * @param pluginExtension the extension used to determine the plugin
  66996. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66997. */
  66998. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66999. if (onProgress === void 0) { onProgress = null; }
  67000. if (pluginExtension === void 0) { pluginExtension = null; }
  67001. return new Promise(function (resolve, reject) {
  67002. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67003. resolve({
  67004. meshes: meshes,
  67005. particleSystems: particleSystems,
  67006. skeletons: skeletons,
  67007. animationGroups: animationGroups
  67008. });
  67009. }, onProgress, function (scene, message, exception) {
  67010. reject(exception || new Error(message));
  67011. });
  67012. });
  67013. };
  67014. /**
  67015. * Load a scene
  67016. * @param rootUrl a string that defines the root url for scene and resources
  67017. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67018. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67019. * @param onSuccess a callback with the scene when import succeeds
  67020. * @param onProgress a callback with a progress event for each file being loaded
  67021. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67022. * @param pluginExtension the extension used to determine the plugin
  67023. * @returns The loaded plugin
  67024. */
  67025. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67026. if (onSuccess === void 0) { onSuccess = null; }
  67027. if (onProgress === void 0) { onProgress = null; }
  67028. if (onError === void 0) { onError = null; }
  67029. if (pluginExtension === void 0) { pluginExtension = null; }
  67030. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67031. };
  67032. /**
  67033. * Load a scene
  67034. * @param rootUrl a string that defines the root url for scene and resources
  67035. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67036. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67037. * @param onProgress a callback with a progress event for each file being loaded
  67038. * @param pluginExtension the extension used to determine the plugin
  67039. * @returns The loaded scene
  67040. */
  67041. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67042. if (onProgress === void 0) { onProgress = null; }
  67043. if (pluginExtension === void 0) { pluginExtension = null; }
  67044. return new Promise(function (resolve, reject) {
  67045. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67046. resolve(scene);
  67047. }, onProgress, function (scene, message, exception) {
  67048. reject(exception || new Error(message));
  67049. }, pluginExtension);
  67050. });
  67051. };
  67052. /**
  67053. * Append a scene
  67054. * @param rootUrl a string that defines the root url for scene and resources
  67055. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67056. * @param scene is the instance of BABYLON.Scene to append to
  67057. * @param onSuccess a callback with the scene when import succeeds
  67058. * @param onProgress a callback with a progress event for each file being loaded
  67059. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67060. * @param pluginExtension the extension used to determine the plugin
  67061. * @returns The loaded plugin
  67062. */
  67063. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67064. if (onSuccess === void 0) { onSuccess = null; }
  67065. if (onProgress === void 0) { onProgress = null; }
  67066. if (onError === void 0) { onError = null; }
  67067. if (pluginExtension === void 0) { pluginExtension = null; }
  67068. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67069. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67070. return null;
  67071. }
  67072. if (SceneLoader.ShowLoadingScreen) {
  67073. scene.getEngine().displayLoadingUI();
  67074. }
  67075. var loadingToken = {};
  67076. scene._addPendingData(loadingToken);
  67077. var disposeHandler = function () {
  67078. scene._removePendingData(loadingToken);
  67079. scene.getEngine().hideLoadingUI();
  67080. };
  67081. var errorHandler = function (message, exception) {
  67082. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67083. if (onError) {
  67084. onError(scene, errorMessage, exception);
  67085. }
  67086. else {
  67087. BABYLON.Tools.Error(errorMessage);
  67088. // should the exception be thrown?
  67089. }
  67090. disposeHandler();
  67091. };
  67092. var progressHandler = onProgress ? function (event) {
  67093. try {
  67094. onProgress(event);
  67095. }
  67096. catch (e) {
  67097. errorHandler("Error in onProgress callback", e);
  67098. }
  67099. } : undefined;
  67100. var successHandler = function () {
  67101. if (onSuccess) {
  67102. try {
  67103. onSuccess(scene);
  67104. }
  67105. catch (e) {
  67106. errorHandler("Error in onSuccess callback", e);
  67107. }
  67108. }
  67109. scene._removePendingData(loadingToken);
  67110. };
  67111. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67112. if (sceneFilename === "") {
  67113. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67114. }
  67115. if (plugin.load) {
  67116. var syncedPlugin = plugin;
  67117. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67118. return;
  67119. }
  67120. scene.loadingPluginName = plugin.name;
  67121. successHandler();
  67122. }
  67123. else {
  67124. var asyncedPlugin = plugin;
  67125. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67126. scene.loadingPluginName = plugin.name;
  67127. successHandler();
  67128. }).catch(function (error) {
  67129. errorHandler(error.message, error);
  67130. });
  67131. }
  67132. if (SceneLoader.ShowLoadingScreen) {
  67133. scene.executeWhenReady(function () {
  67134. scene.getEngine().hideLoadingUI();
  67135. });
  67136. }
  67137. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67138. };
  67139. /**
  67140. * Append a scene
  67141. * @param rootUrl a string that defines the root url for scene and resources
  67142. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67143. * @param scene is the instance of BABYLON.Scene to append to
  67144. * @param onProgress a callback with a progress event for each file being loaded
  67145. * @param pluginExtension the extension used to determine the plugin
  67146. * @returns The given scene
  67147. */
  67148. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67149. if (onProgress === void 0) { onProgress = null; }
  67150. if (pluginExtension === void 0) { pluginExtension = null; }
  67151. return new Promise(function (resolve, reject) {
  67152. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67153. resolve(scene);
  67154. }, onProgress, function (scene, message, exception) {
  67155. reject(exception || new Error(message));
  67156. }, pluginExtension);
  67157. });
  67158. };
  67159. /**
  67160. * Load a scene into an asset container
  67161. * @param rootUrl a string that defines the root url for scene and resources
  67162. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67163. * @param scene is the instance of BABYLON.Scene to append to
  67164. * @param onSuccess a callback with the scene when import succeeds
  67165. * @param onProgress a callback with a progress event for each file being loaded
  67166. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67167. * @param pluginExtension the extension used to determine the plugin
  67168. * @returns The loaded plugin
  67169. */
  67170. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67171. if (onSuccess === void 0) { onSuccess = null; }
  67172. if (onProgress === void 0) { onProgress = null; }
  67173. if (onError === void 0) { onError = null; }
  67174. if (pluginExtension === void 0) { pluginExtension = null; }
  67175. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67176. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67177. return null;
  67178. }
  67179. var loadingToken = {};
  67180. scene._addPendingData(loadingToken);
  67181. var disposeHandler = function () {
  67182. scene._removePendingData(loadingToken);
  67183. };
  67184. var errorHandler = function (message, exception) {
  67185. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67186. if (onError) {
  67187. onError(scene, errorMessage, exception);
  67188. }
  67189. else {
  67190. BABYLON.Tools.Error(errorMessage);
  67191. // should the exception be thrown?
  67192. }
  67193. disposeHandler();
  67194. };
  67195. var progressHandler = onProgress ? function (event) {
  67196. try {
  67197. onProgress(event);
  67198. }
  67199. catch (e) {
  67200. errorHandler("Error in onProgress callback", e);
  67201. }
  67202. } : undefined;
  67203. var successHandler = function (assets) {
  67204. if (onSuccess) {
  67205. try {
  67206. onSuccess(assets);
  67207. }
  67208. catch (e) {
  67209. errorHandler("Error in onSuccess callback", e);
  67210. }
  67211. }
  67212. scene._removePendingData(loadingToken);
  67213. };
  67214. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67215. if (plugin.loadAssetContainer) {
  67216. var syncedPlugin = plugin;
  67217. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67218. if (!assetContainer) {
  67219. return;
  67220. }
  67221. scene.loadingPluginName = plugin.name;
  67222. successHandler(assetContainer);
  67223. }
  67224. else if (plugin.loadAssetContainerAsync) {
  67225. var asyncedPlugin = plugin;
  67226. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67227. scene.loadingPluginName = plugin.name;
  67228. successHandler(assetContainer);
  67229. }).catch(function (error) {
  67230. errorHandler(error.message, error);
  67231. });
  67232. }
  67233. else {
  67234. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67235. }
  67236. if (SceneLoader.ShowLoadingScreen) {
  67237. scene.executeWhenReady(function () {
  67238. scene.getEngine().hideLoadingUI();
  67239. });
  67240. }
  67241. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67242. };
  67243. /**
  67244. * Load a scene into an asset container
  67245. * @param rootUrl a string that defines the root url for scene and resources
  67246. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67247. * @param scene is the instance of BABYLON.Scene to append to
  67248. * @param onProgress a callback with a progress event for each file being loaded
  67249. * @param pluginExtension the extension used to determine the plugin
  67250. * @returns The loaded asset container
  67251. */
  67252. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67253. if (onProgress === void 0) { onProgress = null; }
  67254. if (pluginExtension === void 0) { pluginExtension = null; }
  67255. return new Promise(function (resolve, reject) {
  67256. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67257. resolve(assetContainer);
  67258. }, onProgress, function (scene, message, exception) {
  67259. reject(exception || new Error(message));
  67260. }, pluginExtension);
  67261. });
  67262. };
  67263. // Flags
  67264. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67265. SceneLoader._ShowLoadingScreen = true;
  67266. SceneLoader._CleanBoneMatrixWeights = false;
  67267. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67268. // Members
  67269. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67270. SceneLoader._registeredPlugins = {};
  67271. return SceneLoader;
  67272. }());
  67273. BABYLON.SceneLoader = SceneLoader;
  67274. ;
  67275. })(BABYLON || (BABYLON = {}));
  67276. //# sourceMappingURL=babylon.sceneLoader.js.map
  67277. var BABYLON;
  67278. (function (BABYLON) {
  67279. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67280. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67281. var parsedMaterial = parsedData.materials[index];
  67282. if (parsedMaterial.id === id) {
  67283. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67284. }
  67285. }
  67286. return null;
  67287. };
  67288. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67289. for (var i in names) {
  67290. if (mesh.name === names[i]) {
  67291. hierarchyIds.push(mesh.id);
  67292. return true;
  67293. }
  67294. }
  67295. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67296. hierarchyIds.push(mesh.id);
  67297. return true;
  67298. }
  67299. return false;
  67300. };
  67301. var logOperation = function (operation, producer) {
  67302. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67303. };
  67304. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67305. if (addToScene === void 0) { addToScene = false; }
  67306. var container = new BABYLON.AssetContainer(scene);
  67307. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67308. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67309. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67310. // and avoid problems with multiple concurrent .babylon loads.
  67311. var log = "importScene has failed JSON parse";
  67312. try {
  67313. var parsedData = JSON.parse(data);
  67314. log = "";
  67315. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67316. var index;
  67317. var cache;
  67318. // Lights
  67319. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67320. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67321. var parsedLight = parsedData.lights[index];
  67322. var light = BABYLON.Light.Parse(parsedLight, scene);
  67323. if (light) {
  67324. container.lights.push(light);
  67325. log += (index === 0 ? "\n\tLights:" : "");
  67326. log += "\n\t\t" + light.toString(fullDetails);
  67327. }
  67328. }
  67329. }
  67330. // Animations
  67331. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67332. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67333. var parsedAnimation = parsedData.animations[index];
  67334. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67335. scene.animations.push(animation);
  67336. container.animations.push(animation);
  67337. log += (index === 0 ? "\n\tAnimations:" : "");
  67338. log += "\n\t\t" + animation.toString(fullDetails);
  67339. }
  67340. }
  67341. // Materials
  67342. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67343. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67344. var parsedMaterial = parsedData.materials[index];
  67345. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67346. container.materials.push(mat);
  67347. log += (index === 0 ? "\n\tMaterials:" : "");
  67348. log += "\n\t\t" + mat.toString(fullDetails);
  67349. }
  67350. }
  67351. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67352. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67353. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67354. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67355. container.multiMaterials.push(mmat);
  67356. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67357. log += "\n\t\t" + mmat.toString(fullDetails);
  67358. }
  67359. }
  67360. // Morph targets
  67361. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67362. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67363. var managerData = _a[_i];
  67364. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67365. }
  67366. }
  67367. // Skeletons
  67368. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67369. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67370. var parsedSkeleton = parsedData.skeletons[index];
  67371. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67372. container.skeletons.push(skeleton);
  67373. log += (index === 0 ? "\n\tSkeletons:" : "");
  67374. log += "\n\t\t" + skeleton.toString(fullDetails);
  67375. }
  67376. }
  67377. // Geometries
  67378. var geometries = parsedData.geometries;
  67379. if (geometries !== undefined && geometries !== null) {
  67380. var addedGeometry = new Array();
  67381. // Boxes
  67382. var boxes = geometries.boxes;
  67383. if (boxes !== undefined && boxes !== null) {
  67384. for (index = 0, cache = boxes.length; index < cache; index++) {
  67385. var parsedBox = boxes[index];
  67386. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67387. }
  67388. }
  67389. // Spheres
  67390. var spheres = geometries.spheres;
  67391. if (spheres !== undefined && spheres !== null) {
  67392. for (index = 0, cache = spheres.length; index < cache; index++) {
  67393. var parsedSphere = spheres[index];
  67394. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67395. }
  67396. }
  67397. // Cylinders
  67398. var cylinders = geometries.cylinders;
  67399. if (cylinders !== undefined && cylinders !== null) {
  67400. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67401. var parsedCylinder = cylinders[index];
  67402. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67403. }
  67404. }
  67405. // Toruses
  67406. var toruses = geometries.toruses;
  67407. if (toruses !== undefined && toruses !== null) {
  67408. for (index = 0, cache = toruses.length; index < cache; index++) {
  67409. var parsedTorus = toruses[index];
  67410. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67411. }
  67412. }
  67413. // Grounds
  67414. var grounds = geometries.grounds;
  67415. if (grounds !== undefined && grounds !== null) {
  67416. for (index = 0, cache = grounds.length; index < cache; index++) {
  67417. var parsedGround = grounds[index];
  67418. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67419. }
  67420. }
  67421. // Planes
  67422. var planes = geometries.planes;
  67423. if (planes !== undefined && planes !== null) {
  67424. for (index = 0, cache = planes.length; index < cache; index++) {
  67425. var parsedPlane = planes[index];
  67426. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67427. }
  67428. }
  67429. // TorusKnots
  67430. var torusKnots = geometries.torusKnots;
  67431. if (torusKnots !== undefined && torusKnots !== null) {
  67432. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67433. var parsedTorusKnot = torusKnots[index];
  67434. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67435. }
  67436. }
  67437. // VertexData
  67438. var vertexData = geometries.vertexData;
  67439. if (vertexData !== undefined && vertexData !== null) {
  67440. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67441. var parsedVertexData = vertexData[index];
  67442. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67443. }
  67444. }
  67445. addedGeometry.forEach(function (g) {
  67446. if (g) {
  67447. container.geometries.push(g);
  67448. }
  67449. });
  67450. }
  67451. // Transform nodes
  67452. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67453. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67454. var parsedTransformNode = parsedData.transformNodes[index];
  67455. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67456. container.transformNodes.push(node);
  67457. }
  67458. }
  67459. // Meshes
  67460. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67461. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67462. var parsedMesh = parsedData.meshes[index];
  67463. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67464. container.meshes.push(mesh);
  67465. log += (index === 0 ? "\n\tMeshes:" : "");
  67466. log += "\n\t\t" + mesh.toString(fullDetails);
  67467. }
  67468. }
  67469. // Cameras
  67470. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67471. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67472. var parsedCamera = parsedData.cameras[index];
  67473. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67474. container.cameras.push(camera);
  67475. log += (index === 0 ? "\n\tCameras:" : "");
  67476. log += "\n\t\t" + camera.toString(fullDetails);
  67477. }
  67478. }
  67479. // Browsing all the graph to connect the dots
  67480. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67481. var camera = scene.cameras[index];
  67482. if (camera._waitingParentId) {
  67483. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67484. camera._waitingParentId = null;
  67485. }
  67486. }
  67487. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67488. var light_1 = scene.lights[index];
  67489. if (light_1 && light_1._waitingParentId) {
  67490. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67491. light_1._waitingParentId = null;
  67492. }
  67493. }
  67494. // Sounds
  67495. // TODO: add sound
  67496. var loadedSounds = [];
  67497. var loadedSound;
  67498. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67499. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67500. var parsedSound = parsedData.sounds[index];
  67501. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67502. if (!parsedSound.url)
  67503. parsedSound.url = parsedSound.name;
  67504. if (!loadedSounds[parsedSound.url]) {
  67505. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67506. loadedSounds[parsedSound.url] = loadedSound;
  67507. container.sounds.push(loadedSound);
  67508. }
  67509. else {
  67510. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67511. }
  67512. }
  67513. else {
  67514. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67515. }
  67516. }
  67517. }
  67518. loadedSounds = [];
  67519. // Connect parents & children and parse actions
  67520. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67521. var transformNode = scene.transformNodes[index];
  67522. if (transformNode._waitingParentId) {
  67523. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67524. transformNode._waitingParentId = null;
  67525. }
  67526. }
  67527. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67528. var mesh = scene.meshes[index];
  67529. if (mesh._waitingParentId) {
  67530. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67531. mesh._waitingParentId = null;
  67532. }
  67533. if (mesh._waitingActions) {
  67534. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67535. mesh._waitingActions = null;
  67536. }
  67537. }
  67538. // freeze world matrix application
  67539. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67540. var currentMesh = scene.meshes[index];
  67541. if (currentMesh._waitingFreezeWorldMatrix) {
  67542. currentMesh.freezeWorldMatrix();
  67543. currentMesh._waitingFreezeWorldMatrix = null;
  67544. }
  67545. else {
  67546. currentMesh.computeWorldMatrix(true);
  67547. }
  67548. }
  67549. // Particles Systems
  67550. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67551. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67552. var parsedParticleSystem = parsedData.particleSystems[index];
  67553. if (parsedParticleSystem.activeParticleCount) {
  67554. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67555. container.particleSystems.push(ps);
  67556. }
  67557. else {
  67558. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67559. container.particleSystems.push(ps);
  67560. }
  67561. }
  67562. }
  67563. // Lens flares
  67564. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67565. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67566. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67567. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67568. container.lensFlareSystems.push(lf);
  67569. }
  67570. }
  67571. // Shadows
  67572. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67573. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67574. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67575. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67576. container.shadowGenerators.push(sg);
  67577. }
  67578. }
  67579. // Lights exclusions / inclusions
  67580. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67581. var light_2 = scene.lights[index];
  67582. // Excluded check
  67583. if (light_2._excludedMeshesIds.length > 0) {
  67584. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67585. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67586. if (excludedMesh) {
  67587. light_2.excludedMeshes.push(excludedMesh);
  67588. }
  67589. }
  67590. light_2._excludedMeshesIds = [];
  67591. }
  67592. // Included check
  67593. if (light_2._includedOnlyMeshesIds.length > 0) {
  67594. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67595. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67596. if (includedOnlyMesh) {
  67597. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67598. }
  67599. }
  67600. light_2._includedOnlyMeshesIds = [];
  67601. }
  67602. }
  67603. // Effect layers
  67604. if (parsedData.effectLayers) {
  67605. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67606. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67607. container.effectLayers.push(effectLayer);
  67608. }
  67609. }
  67610. // Actions (scene)
  67611. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67612. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67613. }
  67614. if (!addToScene) {
  67615. container.removeAllFromScene();
  67616. }
  67617. }
  67618. catch (err) {
  67619. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67620. if (onError) {
  67621. onError(msg, err);
  67622. }
  67623. else {
  67624. BABYLON.Tools.Log(msg);
  67625. throw err;
  67626. }
  67627. }
  67628. finally {
  67629. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67630. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67631. }
  67632. }
  67633. return container;
  67634. };
  67635. BABYLON.SceneLoader.RegisterPlugin({
  67636. name: "babylon.js",
  67637. extensions: ".babylon",
  67638. canDirectLoad: function (data) {
  67639. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67640. return true;
  67641. }
  67642. return false;
  67643. },
  67644. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67645. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67646. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67647. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67648. // and avoid problems with multiple concurrent .babylon loads.
  67649. var log = "importMesh has failed JSON parse";
  67650. try {
  67651. var parsedData = JSON.parse(data);
  67652. log = "";
  67653. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67654. if (!meshesNames) {
  67655. meshesNames = null;
  67656. }
  67657. else if (!Array.isArray(meshesNames)) {
  67658. meshesNames = [meshesNames];
  67659. }
  67660. var hierarchyIds = new Array();
  67661. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67662. var loadedSkeletonsIds = [];
  67663. var loadedMaterialsIds = [];
  67664. var index;
  67665. var cache;
  67666. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67667. var parsedMesh = parsedData.meshes[index];
  67668. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67669. if (meshesNames !== null) {
  67670. // Remove found mesh name from list.
  67671. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67672. }
  67673. //Geometry?
  67674. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67675. //does the file contain geometries?
  67676. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67677. //find the correct geometry and add it to the scene
  67678. var found = false;
  67679. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67680. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67681. return;
  67682. }
  67683. else {
  67684. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67685. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67686. switch (geometryType) {
  67687. case "boxes":
  67688. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67689. break;
  67690. case "spheres":
  67691. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67692. break;
  67693. case "cylinders":
  67694. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67695. break;
  67696. case "toruses":
  67697. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67698. break;
  67699. case "grounds":
  67700. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67701. break;
  67702. case "planes":
  67703. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67704. break;
  67705. case "torusKnots":
  67706. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67707. break;
  67708. case "vertexData":
  67709. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67710. break;
  67711. }
  67712. found = true;
  67713. }
  67714. });
  67715. }
  67716. });
  67717. if (found === false) {
  67718. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67719. }
  67720. }
  67721. }
  67722. // Material ?
  67723. if (parsedMesh.materialId) {
  67724. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67725. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67726. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67727. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67728. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67729. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67730. var subMatId = parsedMultiMaterial.materials[matIndex];
  67731. loadedMaterialsIds.push(subMatId);
  67732. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67733. if (mat) {
  67734. log += "\n\tMaterial " + mat.toString(fullDetails);
  67735. }
  67736. }
  67737. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67738. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67739. if (mmat) {
  67740. materialFound = true;
  67741. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67742. }
  67743. break;
  67744. }
  67745. }
  67746. }
  67747. if (materialFound === false) {
  67748. loadedMaterialsIds.push(parsedMesh.materialId);
  67749. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67750. if (!mat) {
  67751. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67752. }
  67753. else {
  67754. log += "\n\tMaterial " + mat.toString(fullDetails);
  67755. }
  67756. }
  67757. }
  67758. // Skeleton ?
  67759. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67760. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67761. if (skeletonAlreadyLoaded === false) {
  67762. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67763. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67764. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67765. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67766. skeletons.push(skeleton);
  67767. loadedSkeletonsIds.push(parsedSkeleton.id);
  67768. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67769. }
  67770. }
  67771. }
  67772. }
  67773. // Morph targets ?
  67774. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67775. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67776. var managerData = _a[_i];
  67777. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67778. }
  67779. }
  67780. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67781. meshes.push(mesh);
  67782. log += "\n\tMesh " + mesh.toString(fullDetails);
  67783. }
  67784. }
  67785. // Connecting parents
  67786. var currentMesh;
  67787. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67788. currentMesh = scene.meshes[index];
  67789. if (currentMesh._waitingParentId) {
  67790. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67791. currentMesh._waitingParentId = null;
  67792. }
  67793. }
  67794. // freeze and compute world matrix application
  67795. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67796. currentMesh = scene.meshes[index];
  67797. if (currentMesh._waitingFreezeWorldMatrix) {
  67798. currentMesh.freezeWorldMatrix();
  67799. currentMesh._waitingFreezeWorldMatrix = null;
  67800. }
  67801. else {
  67802. currentMesh.computeWorldMatrix(true);
  67803. }
  67804. }
  67805. }
  67806. // Particles
  67807. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67808. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67809. var parsedParticleSystem = parsedData.particleSystems[index];
  67810. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67811. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67812. }
  67813. }
  67814. }
  67815. return true;
  67816. }
  67817. catch (err) {
  67818. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67819. if (onError) {
  67820. onError(msg, err);
  67821. }
  67822. else {
  67823. BABYLON.Tools.Log(msg);
  67824. throw err;
  67825. }
  67826. }
  67827. finally {
  67828. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67829. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67830. }
  67831. }
  67832. return false;
  67833. },
  67834. load: function (scene, data, rootUrl, onError) {
  67835. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67836. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67837. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67838. // and avoid problems with multiple concurrent .babylon loads.
  67839. var log = "importScene has failed JSON parse";
  67840. try {
  67841. var parsedData = JSON.parse(data);
  67842. log = "";
  67843. // Scene
  67844. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67845. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67846. }
  67847. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67848. scene.autoClear = parsedData.autoClear;
  67849. }
  67850. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67851. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67852. }
  67853. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67854. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67855. }
  67856. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67857. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67858. }
  67859. // Fog
  67860. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67861. scene.fogMode = parsedData.fogMode;
  67862. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67863. scene.fogStart = parsedData.fogStart;
  67864. scene.fogEnd = parsedData.fogEnd;
  67865. scene.fogDensity = parsedData.fogDensity;
  67866. log += "\tFog mode for scene: ";
  67867. switch (scene.fogMode) {
  67868. // getters not compiling, so using hardcoded
  67869. case 1:
  67870. log += "exp\n";
  67871. break;
  67872. case 2:
  67873. log += "exp2\n";
  67874. break;
  67875. case 3:
  67876. log += "linear\n";
  67877. break;
  67878. }
  67879. }
  67880. //Physics
  67881. if (parsedData.physicsEnabled) {
  67882. var physicsPlugin;
  67883. if (parsedData.physicsEngine === "cannon") {
  67884. physicsPlugin = new BABYLON.CannonJSPlugin();
  67885. }
  67886. else if (parsedData.physicsEngine === "oimo") {
  67887. physicsPlugin = new BABYLON.OimoJSPlugin();
  67888. }
  67889. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67890. //else - default engine, which is currently oimo
  67891. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67892. scene.enablePhysics(physicsGravity, physicsPlugin);
  67893. }
  67894. // Metadata
  67895. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67896. scene.metadata = parsedData.metadata;
  67897. }
  67898. //collisions, if defined. otherwise, default is true
  67899. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67900. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67901. }
  67902. scene.workerCollisions = !!parsedData.workerCollisions;
  67903. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67904. if (!container) {
  67905. return false;
  67906. }
  67907. if (parsedData.autoAnimate) {
  67908. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67909. }
  67910. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67911. scene.setActiveCameraByID(parsedData.activeCameraID);
  67912. }
  67913. // Environment texture
  67914. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67915. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67916. if (parsedData.createDefaultSkybox === true) {
  67917. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67918. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67919. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67920. }
  67921. }
  67922. // Finish
  67923. return true;
  67924. }
  67925. catch (err) {
  67926. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67927. if (onError) {
  67928. onError(msg, err);
  67929. }
  67930. else {
  67931. BABYLON.Tools.Log(msg);
  67932. throw err;
  67933. }
  67934. }
  67935. finally {
  67936. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67937. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67938. }
  67939. }
  67940. return false;
  67941. },
  67942. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67943. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67944. return container;
  67945. }
  67946. });
  67947. })(BABYLON || (BABYLON = {}));
  67948. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67949. var BABYLON;
  67950. (function (BABYLON) {
  67951. var FilesInput = /** @class */ (function () {
  67952. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67953. this.onProcessFileCallback = function () { return true; };
  67954. this._engine = engine;
  67955. this._currentScene = scene;
  67956. this._sceneLoadedCallback = sceneLoadedCallback;
  67957. this._progressCallback = progressCallback;
  67958. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67959. this._textureLoadingCallback = textureLoadingCallback;
  67960. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67961. this._onReloadCallback = onReloadCallback;
  67962. this._errorCallback = errorCallback;
  67963. }
  67964. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67965. var _this = this;
  67966. if (elementToMonitor) {
  67967. this._elementToMonitor = elementToMonitor;
  67968. this._dragEnterHandler = function (e) { _this.drag(e); };
  67969. this._dragOverHandler = function (e) { _this.drag(e); };
  67970. this._dropHandler = function (e) { _this.drop(e); };
  67971. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67972. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67973. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67974. }
  67975. };
  67976. FilesInput.prototype.dispose = function () {
  67977. if (!this._elementToMonitor) {
  67978. return;
  67979. }
  67980. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67981. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67982. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67983. };
  67984. FilesInput.prototype.renderFunction = function () {
  67985. if (this._additionalRenderLoopLogicCallback) {
  67986. this._additionalRenderLoopLogicCallback();
  67987. }
  67988. if (this._currentScene) {
  67989. if (this._textureLoadingCallback) {
  67990. var remaining = this._currentScene.getWaitingItemsCount();
  67991. if (remaining > 0) {
  67992. this._textureLoadingCallback(remaining);
  67993. }
  67994. }
  67995. this._currentScene.render();
  67996. }
  67997. };
  67998. FilesInput.prototype.drag = function (e) {
  67999. e.stopPropagation();
  68000. e.preventDefault();
  68001. };
  68002. FilesInput.prototype.drop = function (eventDrop) {
  68003. eventDrop.stopPropagation();
  68004. eventDrop.preventDefault();
  68005. this.loadFiles(eventDrop);
  68006. };
  68007. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68008. var _this = this;
  68009. var reader = folder.createReader();
  68010. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68011. reader.readEntries(function (entries) {
  68012. remaining.count += entries.length;
  68013. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68014. var entry = entries_1[_i];
  68015. if (entry.isFile) {
  68016. entry.file(function (file) {
  68017. file.correctName = relativePath + file.name;
  68018. files.push(file);
  68019. if (--remaining.count === 0) {
  68020. callback();
  68021. }
  68022. });
  68023. }
  68024. else if (entry.isDirectory) {
  68025. _this._traverseFolder(entry, files, remaining, callback);
  68026. }
  68027. }
  68028. if (--remaining.count) {
  68029. callback();
  68030. }
  68031. });
  68032. };
  68033. FilesInput.prototype._processFiles = function (files) {
  68034. for (var i = 0; i < files.length; i++) {
  68035. var name = files[i].correctName.toLowerCase();
  68036. var extension = name.split('.').pop();
  68037. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68038. continue;
  68039. }
  68040. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68041. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68042. this._sceneFileToLoad = files[i];
  68043. }
  68044. else {
  68045. FilesInput.FilesToLoad[name] = files[i];
  68046. }
  68047. }
  68048. };
  68049. FilesInput.prototype.loadFiles = function (event) {
  68050. var _this = this;
  68051. if (this._startingProcessingFilesCallback)
  68052. this._startingProcessingFilesCallback();
  68053. // Handling data transfer via drag'n'drop
  68054. if (event && event.dataTransfer && event.dataTransfer.files) {
  68055. this._filesToLoad = event.dataTransfer.files;
  68056. }
  68057. // Handling files from input files
  68058. if (event && event.target && event.target.files) {
  68059. this._filesToLoad = event.target.files;
  68060. }
  68061. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68062. var files_1 = new Array();
  68063. var folders = [];
  68064. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68065. for (var i = 0; i < this._filesToLoad.length; i++) {
  68066. var fileToLoad = this._filesToLoad[i];
  68067. var name_1 = fileToLoad.name.toLowerCase();
  68068. var entry = void 0;
  68069. fileToLoad.correctName = name_1;
  68070. if (items) {
  68071. var item = items[i];
  68072. if (item.getAsEntry) {
  68073. entry = item.getAsEntry();
  68074. }
  68075. else if (item.webkitGetAsEntry) {
  68076. entry = item.webkitGetAsEntry();
  68077. }
  68078. }
  68079. if (!entry) {
  68080. files_1.push(fileToLoad);
  68081. }
  68082. else {
  68083. if (entry.isDirectory) {
  68084. folders.push(entry);
  68085. }
  68086. else {
  68087. files_1.push(fileToLoad);
  68088. }
  68089. }
  68090. }
  68091. if (folders.length === 0) {
  68092. this._processFiles(files_1);
  68093. this._processReload();
  68094. }
  68095. else {
  68096. var remaining = { count: folders.length };
  68097. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68098. var folder = folders_1[_i];
  68099. this._traverseFolder(folder, files_1, remaining, function () {
  68100. _this._processFiles(files_1);
  68101. if (remaining.count === 0) {
  68102. _this._processReload();
  68103. }
  68104. });
  68105. }
  68106. }
  68107. }
  68108. };
  68109. FilesInput.prototype._processReload = function () {
  68110. if (this._onReloadCallback) {
  68111. this._onReloadCallback(this._sceneFileToLoad);
  68112. }
  68113. else {
  68114. this.reload();
  68115. }
  68116. };
  68117. FilesInput.prototype.reload = function () {
  68118. var _this = this;
  68119. // If a scene file has been provided
  68120. if (this._sceneFileToLoad) {
  68121. if (this._currentScene) {
  68122. if (BABYLON.Tools.errorsCount > 0) {
  68123. BABYLON.Tools.ClearLogCache();
  68124. }
  68125. this._engine.stopRenderLoop();
  68126. this._currentScene.dispose();
  68127. }
  68128. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68129. if (_this._progressCallback) {
  68130. _this._progressCallback(progress);
  68131. }
  68132. }).then(function (scene) {
  68133. _this._currentScene = scene;
  68134. if (_this._sceneLoadedCallback) {
  68135. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68136. }
  68137. // Wait for textures and shaders to be ready
  68138. _this._currentScene.executeWhenReady(function () {
  68139. _this._engine.runRenderLoop(function () {
  68140. _this.renderFunction();
  68141. });
  68142. });
  68143. }).catch(function (error) {
  68144. if (_this._errorCallback) {
  68145. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68146. }
  68147. });
  68148. }
  68149. else {
  68150. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68151. }
  68152. };
  68153. FilesInput.FilesToLoad = {};
  68154. return FilesInput;
  68155. }());
  68156. BABYLON.FilesInput = FilesInput;
  68157. })(BABYLON || (BABYLON = {}));
  68158. //# sourceMappingURL=babylon.filesInput.js.map
  68159. var BABYLON;
  68160. (function (BABYLON) {
  68161. /**
  68162. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68163. * The underlying implementation relies on an associative array to ensure the best performances.
  68164. * The value can be anything including 'null' but except 'undefined'
  68165. */
  68166. var StringDictionary = /** @class */ (function () {
  68167. function StringDictionary() {
  68168. this._count = 0;
  68169. this._data = {};
  68170. }
  68171. /**
  68172. * This will clear this dictionary and copy the content from the 'source' one.
  68173. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68174. * @param source the dictionary to take the content from and copy to this dictionary
  68175. */
  68176. StringDictionary.prototype.copyFrom = function (source) {
  68177. var _this = this;
  68178. this.clear();
  68179. source.forEach(function (t, v) { return _this.add(t, v); });
  68180. };
  68181. /**
  68182. * Get a value based from its key
  68183. * @param key the given key to get the matching value from
  68184. * @return the value if found, otherwise undefined is returned
  68185. */
  68186. StringDictionary.prototype.get = function (key) {
  68187. var val = this._data[key];
  68188. if (val !== undefined) {
  68189. return val;
  68190. }
  68191. return undefined;
  68192. };
  68193. /**
  68194. * Get a value from its key or add it if it doesn't exist.
  68195. * This method will ensure you that a given key/data will be present in the dictionary.
  68196. * @param key the given key to get the matching value from
  68197. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68198. * The factory will only be invoked if there's no data for the given key.
  68199. * @return the value corresponding to the key.
  68200. */
  68201. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68202. var val = this.get(key);
  68203. if (val !== undefined) {
  68204. return val;
  68205. }
  68206. val = factory(key);
  68207. if (val) {
  68208. this.add(key, val);
  68209. }
  68210. return val;
  68211. };
  68212. /**
  68213. * Get a value from its key if present in the dictionary otherwise add it
  68214. * @param key the key to get the value from
  68215. * @param val if there's no such key/value pair in the dictionary add it with this value
  68216. * @return the value corresponding to the key
  68217. */
  68218. StringDictionary.prototype.getOrAdd = function (key, val) {
  68219. var curVal = this.get(key);
  68220. if (curVal !== undefined) {
  68221. return curVal;
  68222. }
  68223. this.add(key, val);
  68224. return val;
  68225. };
  68226. /**
  68227. * Check if there's a given key in the dictionary
  68228. * @param key the key to check for
  68229. * @return true if the key is present, false otherwise
  68230. */
  68231. StringDictionary.prototype.contains = function (key) {
  68232. return this._data[key] !== undefined;
  68233. };
  68234. /**
  68235. * Add a new key and its corresponding value
  68236. * @param key the key to add
  68237. * @param value the value corresponding to the key
  68238. * @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
  68239. */
  68240. StringDictionary.prototype.add = function (key, value) {
  68241. if (this._data[key] !== undefined) {
  68242. return false;
  68243. }
  68244. this._data[key] = value;
  68245. ++this._count;
  68246. return true;
  68247. };
  68248. StringDictionary.prototype.set = function (key, value) {
  68249. if (this._data[key] === undefined) {
  68250. return false;
  68251. }
  68252. this._data[key] = value;
  68253. return true;
  68254. };
  68255. /**
  68256. * Get the element of the given key and remove it from the dictionary
  68257. * @param key
  68258. */
  68259. StringDictionary.prototype.getAndRemove = function (key) {
  68260. var val = this.get(key);
  68261. if (val !== undefined) {
  68262. delete this._data[key];
  68263. --this._count;
  68264. return val;
  68265. }
  68266. return null;
  68267. };
  68268. /**
  68269. * Remove a key/value from the dictionary.
  68270. * @param key the key to remove
  68271. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68272. */
  68273. StringDictionary.prototype.remove = function (key) {
  68274. if (this.contains(key)) {
  68275. delete this._data[key];
  68276. --this._count;
  68277. return true;
  68278. }
  68279. return false;
  68280. };
  68281. /**
  68282. * Clear the whole content of the dictionary
  68283. */
  68284. StringDictionary.prototype.clear = function () {
  68285. this._data = {};
  68286. this._count = 0;
  68287. };
  68288. Object.defineProperty(StringDictionary.prototype, "count", {
  68289. get: function () {
  68290. return this._count;
  68291. },
  68292. enumerable: true,
  68293. configurable: true
  68294. });
  68295. /**
  68296. * Execute a callback on each key/val of the dictionary.
  68297. * Note that you can remove any element in this dictionary in the callback implementation
  68298. * @param callback the callback to execute on a given key/value pair
  68299. */
  68300. StringDictionary.prototype.forEach = function (callback) {
  68301. for (var cur in this._data) {
  68302. var val = this._data[cur];
  68303. callback(cur, val);
  68304. }
  68305. };
  68306. /**
  68307. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68308. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68309. * Note that you can remove any element in this dictionary in the callback implementation
  68310. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68311. */
  68312. StringDictionary.prototype.first = function (callback) {
  68313. for (var cur in this._data) {
  68314. var val = this._data[cur];
  68315. var res = callback(cur, val);
  68316. if (res) {
  68317. return res;
  68318. }
  68319. }
  68320. return null;
  68321. };
  68322. return StringDictionary;
  68323. }());
  68324. BABYLON.StringDictionary = StringDictionary;
  68325. })(BABYLON || (BABYLON = {}));
  68326. //# sourceMappingURL=babylon.stringDictionary.js.map
  68327. var BABYLON;
  68328. (function (BABYLON) {
  68329. var Tags = /** @class */ (function () {
  68330. function Tags() {
  68331. }
  68332. Tags.EnableFor = function (obj) {
  68333. obj._tags = obj._tags || {};
  68334. obj.hasTags = function () {
  68335. return Tags.HasTags(obj);
  68336. };
  68337. obj.addTags = function (tagsString) {
  68338. return Tags.AddTagsTo(obj, tagsString);
  68339. };
  68340. obj.removeTags = function (tagsString) {
  68341. return Tags.RemoveTagsFrom(obj, tagsString);
  68342. };
  68343. obj.matchesTagsQuery = function (tagsQuery) {
  68344. return Tags.MatchesQuery(obj, tagsQuery);
  68345. };
  68346. };
  68347. Tags.DisableFor = function (obj) {
  68348. delete obj._tags;
  68349. delete obj.hasTags;
  68350. delete obj.addTags;
  68351. delete obj.removeTags;
  68352. delete obj.matchesTagsQuery;
  68353. };
  68354. Tags.HasTags = function (obj) {
  68355. if (!obj._tags) {
  68356. return false;
  68357. }
  68358. return !BABYLON.Tools.IsEmpty(obj._tags);
  68359. };
  68360. Tags.GetTags = function (obj, asString) {
  68361. if (asString === void 0) { asString = true; }
  68362. if (!obj._tags) {
  68363. return null;
  68364. }
  68365. if (asString) {
  68366. var tagsArray = [];
  68367. for (var tag in obj._tags) {
  68368. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68369. tagsArray.push(tag);
  68370. }
  68371. }
  68372. return tagsArray.join(" ");
  68373. }
  68374. else {
  68375. return obj._tags;
  68376. }
  68377. };
  68378. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68379. // a tag cannot start with '||', '&&', and '!'
  68380. // it cannot contain whitespaces
  68381. Tags.AddTagsTo = function (obj, tagsString) {
  68382. if (!tagsString) {
  68383. return;
  68384. }
  68385. if (typeof tagsString !== "string") {
  68386. return;
  68387. }
  68388. var tags = tagsString.split(" ");
  68389. tags.forEach(function (tag, index, array) {
  68390. Tags._AddTagTo(obj, tag);
  68391. });
  68392. };
  68393. Tags._AddTagTo = function (obj, tag) {
  68394. tag = tag.trim();
  68395. if (tag === "" || tag === "true" || tag === "false") {
  68396. return;
  68397. }
  68398. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68399. return;
  68400. }
  68401. Tags.EnableFor(obj);
  68402. obj._tags[tag] = true;
  68403. };
  68404. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68405. if (!Tags.HasTags(obj)) {
  68406. return;
  68407. }
  68408. var tags = tagsString.split(" ");
  68409. for (var t in tags) {
  68410. Tags._RemoveTagFrom(obj, tags[t]);
  68411. }
  68412. };
  68413. Tags._RemoveTagFrom = function (obj, tag) {
  68414. delete obj._tags[tag];
  68415. };
  68416. Tags.MatchesQuery = function (obj, tagsQuery) {
  68417. if (tagsQuery === undefined) {
  68418. return true;
  68419. }
  68420. if (tagsQuery === "") {
  68421. return Tags.HasTags(obj);
  68422. }
  68423. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68424. };
  68425. return Tags;
  68426. }());
  68427. BABYLON.Tags = Tags;
  68428. })(BABYLON || (BABYLON = {}));
  68429. //# sourceMappingURL=babylon.tags.js.map
  68430. var BABYLON;
  68431. (function (BABYLON) {
  68432. /**
  68433. * Class used to evalaute queries containing `and` and `or` operators
  68434. */
  68435. var AndOrNotEvaluator = /** @class */ (function () {
  68436. function AndOrNotEvaluator() {
  68437. }
  68438. /**
  68439. * Evaluate a query
  68440. * @param query defines the query to evaluate
  68441. * @param evaluateCallback defines the callback used to filter result
  68442. * @returns true if the query matches
  68443. */
  68444. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68445. if (!query.match(/\([^\(\)]*\)/g)) {
  68446. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68447. }
  68448. else {
  68449. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68450. // remove parenthesis
  68451. r = r.slice(1, r.length - 1);
  68452. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68453. });
  68454. }
  68455. if (query === "true") {
  68456. return true;
  68457. }
  68458. if (query === "false") {
  68459. return false;
  68460. }
  68461. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68462. };
  68463. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68464. evaluateCallback = evaluateCallback || (function (r) {
  68465. return r === "true" ? true : false;
  68466. });
  68467. var result;
  68468. var or = parenthesisContent.split("||");
  68469. for (var i in or) {
  68470. if (or.hasOwnProperty(i)) {
  68471. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68472. var and = ori.split("&&");
  68473. if (and.length > 1) {
  68474. for (var j = 0; j < and.length; ++j) {
  68475. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68476. if (andj !== "true" && andj !== "false") {
  68477. if (andj[0] === "!") {
  68478. result = !evaluateCallback(andj.substring(1));
  68479. }
  68480. else {
  68481. result = evaluateCallback(andj);
  68482. }
  68483. }
  68484. else {
  68485. result = andj === "true" ? true : false;
  68486. }
  68487. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68488. ori = "false";
  68489. break;
  68490. }
  68491. }
  68492. }
  68493. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68494. result = true;
  68495. break;
  68496. }
  68497. // result equals false (or undefined)
  68498. if (ori !== "true" && ori !== "false") {
  68499. if (ori[0] === "!") {
  68500. result = !evaluateCallback(ori.substring(1));
  68501. }
  68502. else {
  68503. result = evaluateCallback(ori);
  68504. }
  68505. }
  68506. else {
  68507. result = ori === "true" ? true : false;
  68508. }
  68509. }
  68510. }
  68511. // the whole parenthesis scope is replaced by 'true' or 'false'
  68512. return result ? "true" : "false";
  68513. };
  68514. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68515. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68516. // remove whitespaces
  68517. r = r.replace(/[\s]/g, function () { return ""; });
  68518. return r.length % 2 ? "!" : "";
  68519. });
  68520. booleanString = booleanString.trim();
  68521. if (booleanString === "!true") {
  68522. booleanString = "false";
  68523. }
  68524. else if (booleanString === "!false") {
  68525. booleanString = "true";
  68526. }
  68527. return booleanString;
  68528. };
  68529. return AndOrNotEvaluator;
  68530. }());
  68531. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68532. })(BABYLON || (BABYLON = {}));
  68533. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68534. var BABYLON;
  68535. (function (BABYLON) {
  68536. /**
  68537. * Class used to enable access to IndexedDB
  68538. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68539. */
  68540. var Database = /** @class */ (function () {
  68541. /**
  68542. * Creates a new Database
  68543. * @param urlToScene defines the url to load the scene
  68544. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68545. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68546. */
  68547. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68548. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68549. var _this = this;
  68550. // Handling various flavors of prefixed version of IndexedDB
  68551. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68552. this.callbackManifestChecked = callbackManifestChecked;
  68553. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68554. this.db = null;
  68555. this._enableSceneOffline = false;
  68556. this._enableTexturesOffline = false;
  68557. this.manifestVersionFound = 0;
  68558. this.mustUpdateRessources = false;
  68559. this.hasReachedQuota = false;
  68560. if (!Database.IDBStorageEnabled) {
  68561. this.callbackManifestChecked(true);
  68562. }
  68563. else {
  68564. if (disableManifestCheck) {
  68565. this._enableSceneOffline = true;
  68566. this._enableTexturesOffline = true;
  68567. this.manifestVersionFound = 1;
  68568. BABYLON.Tools.SetImmediate(function () {
  68569. _this.callbackManifestChecked(true);
  68570. });
  68571. }
  68572. else {
  68573. this._checkManifestFile();
  68574. }
  68575. }
  68576. }
  68577. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68578. /**
  68579. * Gets a boolean indicating if scene must be saved in the database
  68580. */
  68581. get: function () {
  68582. return this._enableSceneOffline;
  68583. },
  68584. enumerable: true,
  68585. configurable: true
  68586. });
  68587. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68588. /**
  68589. * Gets a boolean indicating if textures must be saved in the database
  68590. */
  68591. get: function () {
  68592. return this._enableTexturesOffline;
  68593. },
  68594. enumerable: true,
  68595. configurable: true
  68596. });
  68597. Database.prototype._checkManifestFile = function () {
  68598. var _this = this;
  68599. var noManifestFile = function () {
  68600. _this._enableSceneOffline = false;
  68601. _this._enableTexturesOffline = false;
  68602. _this.callbackManifestChecked(false);
  68603. };
  68604. var timeStampUsed = false;
  68605. var manifestURL = this.currentSceneUrl + ".manifest";
  68606. var xhr = new XMLHttpRequest();
  68607. if (navigator.onLine) {
  68608. // Adding a timestamp to by-pass browsers' cache
  68609. timeStampUsed = true;
  68610. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68611. }
  68612. xhr.open("GET", manifestURL, true);
  68613. xhr.addEventListener("load", function () {
  68614. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68615. try {
  68616. var manifestFile = JSON.parse(xhr.response);
  68617. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68618. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68619. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68620. _this.manifestVersionFound = manifestFile.version;
  68621. }
  68622. if (_this.callbackManifestChecked) {
  68623. _this.callbackManifestChecked(true);
  68624. }
  68625. }
  68626. catch (ex) {
  68627. noManifestFile();
  68628. }
  68629. }
  68630. else {
  68631. noManifestFile();
  68632. }
  68633. }, false);
  68634. xhr.addEventListener("error", function (event) {
  68635. if (timeStampUsed) {
  68636. timeStampUsed = false;
  68637. // Let's retry without the timeStamp
  68638. // It could fail when coupled with HTML5 Offline API
  68639. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68640. xhr.open("GET", retryManifestURL, true);
  68641. xhr.send();
  68642. }
  68643. else {
  68644. noManifestFile();
  68645. }
  68646. }, false);
  68647. try {
  68648. xhr.send();
  68649. }
  68650. catch (ex) {
  68651. BABYLON.Tools.Error("Error on XHR send request.");
  68652. this.callbackManifestChecked(false);
  68653. }
  68654. };
  68655. /**
  68656. * Open the database and make it available
  68657. * @param successCallback defines the callback to call on success
  68658. * @param errorCallback defines the callback to call on error
  68659. */
  68660. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68661. var _this = this;
  68662. var handleError = function () {
  68663. _this.isSupported = false;
  68664. if (errorCallback)
  68665. errorCallback();
  68666. };
  68667. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68668. // Your browser doesn't support IndexedDB
  68669. this.isSupported = false;
  68670. if (errorCallback)
  68671. errorCallback();
  68672. }
  68673. else {
  68674. // If the DB hasn't been opened or created yet
  68675. if (!this.db) {
  68676. this.hasReachedQuota = false;
  68677. this.isSupported = true;
  68678. var request = this.idbFactory.open("babylonjs", 1);
  68679. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68680. request.onerror = function (event) {
  68681. handleError();
  68682. };
  68683. // executes when a version change transaction cannot complete due to other active transactions
  68684. request.onblocked = function (event) {
  68685. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68686. handleError();
  68687. };
  68688. // DB has been opened successfully
  68689. request.onsuccess = function (event) {
  68690. _this.db = request.result;
  68691. successCallback();
  68692. };
  68693. // Initialization of the DB. Creating Scenes & Textures stores
  68694. request.onupgradeneeded = function (event) {
  68695. _this.db = (event.target).result;
  68696. if (_this.db) {
  68697. try {
  68698. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68699. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68700. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68701. }
  68702. catch (ex) {
  68703. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68704. handleError();
  68705. }
  68706. }
  68707. };
  68708. }
  68709. // DB has already been created and opened
  68710. else {
  68711. if (successCallback)
  68712. successCallback();
  68713. }
  68714. }
  68715. };
  68716. /**
  68717. * Loads an image from the database
  68718. * @param url defines the url to load from
  68719. * @param image defines the target DOM image
  68720. */
  68721. Database.prototype.loadImageFromDB = function (url, image) {
  68722. var _this = this;
  68723. var completeURL = Database._ReturnFullUrlLocation(url);
  68724. var saveAndLoadImage = function () {
  68725. if (!_this.hasReachedQuota && _this.db !== null) {
  68726. // the texture is not yet in the DB, let's try to save it
  68727. _this._saveImageIntoDBAsync(completeURL, image);
  68728. }
  68729. // If the texture is not in the DB and we've reached the DB quota limit
  68730. // let's load it directly from the web
  68731. else {
  68732. image.src = url;
  68733. }
  68734. };
  68735. if (!this.mustUpdateRessources) {
  68736. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68737. }
  68738. // First time we're download the images or update requested in the manifest file by a version change
  68739. else {
  68740. saveAndLoadImage();
  68741. }
  68742. };
  68743. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68744. if (this.isSupported && this.db !== null) {
  68745. var texture;
  68746. var transaction = this.db.transaction(["textures"]);
  68747. transaction.onabort = function (event) {
  68748. image.src = url;
  68749. };
  68750. transaction.oncomplete = function (event) {
  68751. var blobTextureURL;
  68752. if (texture) {
  68753. var URL = window.URL || window.webkitURL;
  68754. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68755. image.onerror = function () {
  68756. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68757. image.src = url;
  68758. };
  68759. image.src = blobTextureURL;
  68760. }
  68761. else {
  68762. notInDBCallback();
  68763. }
  68764. };
  68765. var getRequest = transaction.objectStore("textures").get(url);
  68766. getRequest.onsuccess = function (event) {
  68767. texture = (event.target).result;
  68768. };
  68769. getRequest.onerror = function (event) {
  68770. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68771. image.src = url;
  68772. };
  68773. }
  68774. else {
  68775. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68776. image.src = url;
  68777. }
  68778. };
  68779. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68780. var _this = this;
  68781. if (this.isSupported) {
  68782. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68783. var generateBlobUrl = function () {
  68784. var blobTextureURL;
  68785. if (blob) {
  68786. var URL = window.URL || window.webkitURL;
  68787. try {
  68788. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68789. }
  68790. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68791. catch (ex) {
  68792. blobTextureURL = URL.createObjectURL(blob);
  68793. }
  68794. }
  68795. if (blobTextureURL) {
  68796. image.src = blobTextureURL;
  68797. }
  68798. };
  68799. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68800. var xhr = new XMLHttpRequest(), blob;
  68801. xhr.open("GET", url, true);
  68802. xhr.responseType = "blob";
  68803. xhr.addEventListener("load", function () {
  68804. if (xhr.status === 200 && _this.db) {
  68805. // Blob as response (XHR2)
  68806. blob = xhr.response;
  68807. var transaction = _this.db.transaction(["textures"], "readwrite");
  68808. // the transaction could abort because of a QuotaExceededError error
  68809. transaction.onabort = function (event) {
  68810. try {
  68811. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68812. var srcElement = (event.srcElement || event.target);
  68813. var error = srcElement.error;
  68814. if (error && error.name === "QuotaExceededError") {
  68815. _this.hasReachedQuota = true;
  68816. }
  68817. }
  68818. catch (ex) { }
  68819. generateBlobUrl();
  68820. };
  68821. transaction.oncomplete = function (event) {
  68822. generateBlobUrl();
  68823. };
  68824. var newTexture = { textureUrl: url, data: blob };
  68825. try {
  68826. // Put the blob into the dabase
  68827. var addRequest = transaction.objectStore("textures").put(newTexture);
  68828. addRequest.onsuccess = function (event) {
  68829. };
  68830. addRequest.onerror = function (event) {
  68831. generateBlobUrl();
  68832. };
  68833. }
  68834. catch (ex) {
  68835. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68836. if (ex.code === 25) {
  68837. Database.IsUASupportingBlobStorage = false;
  68838. }
  68839. image.src = url;
  68840. }
  68841. }
  68842. else {
  68843. image.src = url;
  68844. }
  68845. }, false);
  68846. xhr.addEventListener("error", function (event) {
  68847. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68848. image.src = url;
  68849. }, false);
  68850. xhr.send();
  68851. }
  68852. else {
  68853. image.src = url;
  68854. }
  68855. }
  68856. else {
  68857. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68858. image.src = url;
  68859. }
  68860. };
  68861. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68862. var _this = this;
  68863. var updateVersion = function () {
  68864. // the version is not yet in the DB or we need to update it
  68865. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68866. };
  68867. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68868. };
  68869. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68870. var _this = this;
  68871. if (this.isSupported && this.db) {
  68872. var version;
  68873. try {
  68874. var transaction = this.db.transaction(["versions"]);
  68875. transaction.oncomplete = function (event) {
  68876. if (version) {
  68877. // If the version in the JSON file is > than the version in DB
  68878. if (_this.manifestVersionFound > version.data) {
  68879. _this.mustUpdateRessources = true;
  68880. updateInDBCallback();
  68881. }
  68882. else {
  68883. callback(version.data);
  68884. }
  68885. }
  68886. // version was not found in DB
  68887. else {
  68888. _this.mustUpdateRessources = true;
  68889. updateInDBCallback();
  68890. }
  68891. };
  68892. transaction.onabort = function (event) {
  68893. callback(-1);
  68894. };
  68895. var getRequest = transaction.objectStore("versions").get(url);
  68896. getRequest.onsuccess = function (event) {
  68897. version = (event.target).result;
  68898. };
  68899. getRequest.onerror = function (event) {
  68900. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68901. callback(-1);
  68902. };
  68903. }
  68904. catch (ex) {
  68905. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68906. callback(-1);
  68907. }
  68908. }
  68909. else {
  68910. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68911. callback(-1);
  68912. }
  68913. };
  68914. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68915. var _this = this;
  68916. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68917. try {
  68918. // Open a transaction to the database
  68919. var transaction = this.db.transaction(["versions"], "readwrite");
  68920. // the transaction could abort because of a QuotaExceededError error
  68921. transaction.onabort = function (event) {
  68922. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68923. var error = event.srcElement['error'];
  68924. if (error && error.name === "QuotaExceededError") {
  68925. _this.hasReachedQuota = true;
  68926. }
  68927. }
  68928. catch (ex) { }
  68929. callback(-1);
  68930. };
  68931. transaction.oncomplete = function (event) {
  68932. callback(_this.manifestVersionFound);
  68933. };
  68934. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68935. // Put the scene into the database
  68936. var addRequest = transaction.objectStore("versions").put(newVersion);
  68937. addRequest.onsuccess = function (event) {
  68938. };
  68939. addRequest.onerror = function (event) {
  68940. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68941. };
  68942. }
  68943. catch (ex) {
  68944. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68945. callback(-1);
  68946. }
  68947. }
  68948. else {
  68949. callback(-1);
  68950. }
  68951. };
  68952. /**
  68953. * Loads a file from database
  68954. * @param url defines the URL to load from
  68955. * @param sceneLoaded defines a callback to call on success
  68956. * @param progressCallBack defines a callback to call when progress changed
  68957. * @param errorCallback defines a callback to call on error
  68958. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68959. */
  68960. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68961. var _this = this;
  68962. var completeUrl = Database._ReturnFullUrlLocation(url);
  68963. var saveAndLoadFile = function () {
  68964. // the scene is not yet in the DB, let's try to save it
  68965. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68966. };
  68967. this._checkVersionFromDB(completeUrl, function (version) {
  68968. if (version !== -1) {
  68969. if (!_this.mustUpdateRessources) {
  68970. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68971. }
  68972. else {
  68973. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68974. }
  68975. }
  68976. else {
  68977. if (errorCallback) {
  68978. errorCallback();
  68979. }
  68980. }
  68981. });
  68982. };
  68983. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68984. if (this.isSupported && this.db) {
  68985. var targetStore;
  68986. if (url.indexOf(".babylon") !== -1) {
  68987. targetStore = "scenes";
  68988. }
  68989. else {
  68990. targetStore = "textures";
  68991. }
  68992. var file;
  68993. var transaction = this.db.transaction([targetStore]);
  68994. transaction.oncomplete = function (event) {
  68995. if (file) {
  68996. callback(file.data);
  68997. }
  68998. // file was not found in DB
  68999. else {
  69000. notInDBCallback();
  69001. }
  69002. };
  69003. transaction.onabort = function (event) {
  69004. notInDBCallback();
  69005. };
  69006. var getRequest = transaction.objectStore(targetStore).get(url);
  69007. getRequest.onsuccess = function (event) {
  69008. file = (event.target).result;
  69009. };
  69010. getRequest.onerror = function (event) {
  69011. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69012. notInDBCallback();
  69013. };
  69014. }
  69015. else {
  69016. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69017. callback();
  69018. }
  69019. };
  69020. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69021. var _this = this;
  69022. if (this.isSupported) {
  69023. var targetStore;
  69024. if (url.indexOf(".babylon") !== -1) {
  69025. targetStore = "scenes";
  69026. }
  69027. else {
  69028. targetStore = "textures";
  69029. }
  69030. // Create XHR
  69031. var xhr = new XMLHttpRequest();
  69032. var fileData;
  69033. xhr.open("GET", url, true);
  69034. if (useArrayBuffer) {
  69035. xhr.responseType = "arraybuffer";
  69036. }
  69037. if (progressCallback) {
  69038. xhr.onprogress = progressCallback;
  69039. }
  69040. xhr.addEventListener("load", function () {
  69041. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69042. // Blob as response (XHR2)
  69043. //fileData = xhr.responseText;
  69044. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69045. if (!_this.hasReachedQuota && _this.db) {
  69046. // Open a transaction to the database
  69047. var transaction = _this.db.transaction([targetStore], "readwrite");
  69048. // the transaction could abort because of a QuotaExceededError error
  69049. transaction.onabort = function (event) {
  69050. try {
  69051. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69052. var error = event.srcElement['error'];
  69053. if (error && error.name === "QuotaExceededError") {
  69054. _this.hasReachedQuota = true;
  69055. }
  69056. }
  69057. catch (ex) { }
  69058. callback(fileData);
  69059. };
  69060. transaction.oncomplete = function (event) {
  69061. callback(fileData);
  69062. };
  69063. var newFile;
  69064. if (targetStore === "scenes") {
  69065. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69066. }
  69067. else {
  69068. newFile = { textureUrl: url, data: fileData };
  69069. }
  69070. try {
  69071. // Put the scene into the database
  69072. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69073. addRequest.onsuccess = function (event) {
  69074. };
  69075. addRequest.onerror = function (event) {
  69076. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69077. };
  69078. }
  69079. catch (ex) {
  69080. callback(fileData);
  69081. }
  69082. }
  69083. else {
  69084. callback(fileData);
  69085. }
  69086. }
  69087. else {
  69088. callback();
  69089. }
  69090. }, false);
  69091. xhr.addEventListener("error", function (event) {
  69092. BABYLON.Tools.Error("error on XHR request.");
  69093. callback();
  69094. }, false);
  69095. xhr.send();
  69096. }
  69097. else {
  69098. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69099. callback();
  69100. }
  69101. };
  69102. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69103. Database.IsUASupportingBlobStorage = true;
  69104. /** Gets a boolean indicating if Database storate is enabled */
  69105. Database.IDBStorageEnabled = true;
  69106. Database._ParseURL = function (url) {
  69107. var a = document.createElement('a');
  69108. a.href = url;
  69109. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69110. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69111. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69112. return absLocation;
  69113. };
  69114. Database._ReturnFullUrlLocation = function (url) {
  69115. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69116. return (Database._ParseURL(window.location.href) + url);
  69117. }
  69118. else {
  69119. return url;
  69120. }
  69121. };
  69122. return Database;
  69123. }());
  69124. BABYLON.Database = Database;
  69125. })(BABYLON || (BABYLON = {}));
  69126. //# sourceMappingURL=babylon.database.js.map
  69127. var BABYLON;
  69128. (function (BABYLON) {
  69129. var FresnelParameters = /** @class */ (function () {
  69130. function FresnelParameters() {
  69131. this._isEnabled = true;
  69132. this.leftColor = BABYLON.Color3.White();
  69133. this.rightColor = BABYLON.Color3.Black();
  69134. this.bias = 0;
  69135. this.power = 1;
  69136. }
  69137. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69138. get: function () {
  69139. return this._isEnabled;
  69140. },
  69141. set: function (value) {
  69142. if (this._isEnabled === value) {
  69143. return;
  69144. }
  69145. this._isEnabled = value;
  69146. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69147. },
  69148. enumerable: true,
  69149. configurable: true
  69150. });
  69151. FresnelParameters.prototype.clone = function () {
  69152. var newFresnelParameters = new FresnelParameters();
  69153. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69154. return newFresnelParameters;
  69155. };
  69156. FresnelParameters.prototype.serialize = function () {
  69157. var serializationObject = {};
  69158. serializationObject.isEnabled = this.isEnabled;
  69159. serializationObject.leftColor = this.leftColor.asArray();
  69160. serializationObject.rightColor = this.rightColor.asArray();
  69161. serializationObject.bias = this.bias;
  69162. serializationObject.power = this.power;
  69163. return serializationObject;
  69164. };
  69165. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69166. var fresnelParameters = new FresnelParameters();
  69167. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69168. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69169. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69170. fresnelParameters.bias = parsedFresnelParameters.bias;
  69171. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69172. return fresnelParameters;
  69173. };
  69174. return FresnelParameters;
  69175. }());
  69176. BABYLON.FresnelParameters = FresnelParameters;
  69177. })(BABYLON || (BABYLON = {}));
  69178. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69179. var BABYLON;
  69180. (function (BABYLON) {
  69181. var MultiMaterial = /** @class */ (function (_super) {
  69182. __extends(MultiMaterial, _super);
  69183. function MultiMaterial(name, scene) {
  69184. var _this = _super.call(this, name, scene, true) || this;
  69185. scene.multiMaterials.push(_this);
  69186. _this.subMaterials = new Array();
  69187. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69188. return _this;
  69189. }
  69190. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69191. get: function () {
  69192. return this._subMaterials;
  69193. },
  69194. set: function (value) {
  69195. this._subMaterials = value;
  69196. this._hookArray(value);
  69197. },
  69198. enumerable: true,
  69199. configurable: true
  69200. });
  69201. MultiMaterial.prototype._hookArray = function (array) {
  69202. var _this = this;
  69203. var oldPush = array.push;
  69204. array.push = function () {
  69205. var items = [];
  69206. for (var _i = 0; _i < arguments.length; _i++) {
  69207. items[_i] = arguments[_i];
  69208. }
  69209. var result = oldPush.apply(array, items);
  69210. _this._markAllSubMeshesAsTexturesDirty();
  69211. return result;
  69212. };
  69213. var oldSplice = array.splice;
  69214. array.splice = function (index, deleteCount) {
  69215. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69216. _this._markAllSubMeshesAsTexturesDirty();
  69217. return deleted;
  69218. };
  69219. };
  69220. // Properties
  69221. MultiMaterial.prototype.getSubMaterial = function (index) {
  69222. if (index < 0 || index >= this.subMaterials.length) {
  69223. return this.getScene().defaultMaterial;
  69224. }
  69225. return this.subMaterials[index];
  69226. };
  69227. MultiMaterial.prototype.getActiveTextures = function () {
  69228. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69229. if (subMaterial) {
  69230. return subMaterial.getActiveTextures();
  69231. }
  69232. else {
  69233. return [];
  69234. }
  69235. }));
  69236. var _a;
  69237. };
  69238. // Methods
  69239. MultiMaterial.prototype.getClassName = function () {
  69240. return "MultiMaterial";
  69241. };
  69242. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69243. for (var index = 0; index < this.subMaterials.length; index++) {
  69244. var subMaterial = this.subMaterials[index];
  69245. if (subMaterial) {
  69246. if (subMaterial.storeEffectOnSubMeshes) {
  69247. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69248. return false;
  69249. }
  69250. continue;
  69251. }
  69252. if (!subMaterial.isReady(mesh)) {
  69253. return false;
  69254. }
  69255. }
  69256. }
  69257. return true;
  69258. };
  69259. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69260. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69261. for (var index = 0; index < this.subMaterials.length; index++) {
  69262. var subMaterial = null;
  69263. var current = this.subMaterials[index];
  69264. if (cloneChildren && current) {
  69265. subMaterial = current.clone(name + "-" + current.name);
  69266. }
  69267. else {
  69268. subMaterial = this.subMaterials[index];
  69269. }
  69270. newMultiMaterial.subMaterials.push(subMaterial);
  69271. }
  69272. return newMultiMaterial;
  69273. };
  69274. MultiMaterial.prototype.serialize = function () {
  69275. var serializationObject = {};
  69276. serializationObject.name = this.name;
  69277. serializationObject.id = this.id;
  69278. if (BABYLON.Tags) {
  69279. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69280. }
  69281. serializationObject.materials = [];
  69282. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69283. var subMat = this.subMaterials[matIndex];
  69284. if (subMat) {
  69285. serializationObject.materials.push(subMat.id);
  69286. }
  69287. else {
  69288. serializationObject.materials.push(null);
  69289. }
  69290. }
  69291. return serializationObject;
  69292. };
  69293. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69294. var scene = this.getScene();
  69295. if (!scene) {
  69296. return;
  69297. }
  69298. var index = scene.multiMaterials.indexOf(this);
  69299. if (index >= 0) {
  69300. scene.multiMaterials.splice(index, 1);
  69301. }
  69302. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69303. };
  69304. return MultiMaterial;
  69305. }(BABYLON.Material));
  69306. BABYLON.MultiMaterial = MultiMaterial;
  69307. })(BABYLON || (BABYLON = {}));
  69308. //# sourceMappingURL=babylon.multiMaterial.js.map
  69309. var BABYLON;
  69310. (function (BABYLON) {
  69311. var FreeCameraTouchInput = /** @class */ (function () {
  69312. function FreeCameraTouchInput() {
  69313. this._offsetX = null;
  69314. this._offsetY = null;
  69315. this._pointerPressed = new Array();
  69316. this.touchAngularSensibility = 200000.0;
  69317. this.touchMoveSensibility = 250.0;
  69318. }
  69319. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69320. var _this = this;
  69321. var previousPosition = null;
  69322. if (this._pointerInput === undefined) {
  69323. this._onLostFocus = function (evt) {
  69324. _this._offsetX = null;
  69325. _this._offsetY = null;
  69326. };
  69327. this._pointerInput = function (p, s) {
  69328. var evt = p.event;
  69329. if (evt.pointerType === "mouse") {
  69330. return;
  69331. }
  69332. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69333. if (!noPreventDefault) {
  69334. evt.preventDefault();
  69335. }
  69336. _this._pointerPressed.push(evt.pointerId);
  69337. if (_this._pointerPressed.length !== 1) {
  69338. return;
  69339. }
  69340. previousPosition = {
  69341. x: evt.clientX,
  69342. y: evt.clientY
  69343. };
  69344. }
  69345. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69346. if (!noPreventDefault) {
  69347. evt.preventDefault();
  69348. }
  69349. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69350. if (index === -1) {
  69351. return;
  69352. }
  69353. _this._pointerPressed.splice(index, 1);
  69354. if (index != 0) {
  69355. return;
  69356. }
  69357. previousPosition = null;
  69358. _this._offsetX = null;
  69359. _this._offsetY = null;
  69360. }
  69361. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69362. if (!noPreventDefault) {
  69363. evt.preventDefault();
  69364. }
  69365. if (!previousPosition) {
  69366. return;
  69367. }
  69368. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69369. if (index != 0) {
  69370. return;
  69371. }
  69372. _this._offsetX = evt.clientX - previousPosition.x;
  69373. _this._offsetY = -(evt.clientY - previousPosition.y);
  69374. }
  69375. };
  69376. }
  69377. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69378. if (this._onLostFocus) {
  69379. element.addEventListener("blur", this._onLostFocus);
  69380. }
  69381. };
  69382. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69383. if (this._pointerInput && element) {
  69384. if (this._observer) {
  69385. this.camera.getScene().onPointerObservable.remove(this._observer);
  69386. this._observer = null;
  69387. }
  69388. if (this._onLostFocus) {
  69389. element.removeEventListener("blur", this._onLostFocus);
  69390. this._onLostFocus = null;
  69391. }
  69392. this._pointerPressed = [];
  69393. this._offsetX = null;
  69394. this._offsetY = null;
  69395. }
  69396. };
  69397. FreeCameraTouchInput.prototype.checkInputs = function () {
  69398. if (this._offsetX && this._offsetY) {
  69399. var camera = this.camera;
  69400. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69401. if (this._pointerPressed.length > 1) {
  69402. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69403. }
  69404. else {
  69405. var speed = camera._computeLocalCameraSpeed();
  69406. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69407. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69408. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69409. }
  69410. }
  69411. };
  69412. FreeCameraTouchInput.prototype.getClassName = function () {
  69413. return "FreeCameraTouchInput";
  69414. };
  69415. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69416. return "touch";
  69417. };
  69418. __decorate([
  69419. BABYLON.serialize()
  69420. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69421. __decorate([
  69422. BABYLON.serialize()
  69423. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69424. return FreeCameraTouchInput;
  69425. }());
  69426. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69427. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69428. })(BABYLON || (BABYLON = {}));
  69429. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69430. var BABYLON;
  69431. (function (BABYLON) {
  69432. // We're mainly based on the logic defined into the FreeCamera code
  69433. var TouchCamera = /** @class */ (function (_super) {
  69434. __extends(TouchCamera, _super);
  69435. //-- end properties for backward compatibility for inputs
  69436. function TouchCamera(name, position, scene) {
  69437. var _this = _super.call(this, name, position, scene) || this;
  69438. _this.inputs.addTouch();
  69439. _this._setupInputs();
  69440. return _this;
  69441. }
  69442. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69443. //-- Begin properties for backward compatibility for inputs
  69444. get: function () {
  69445. var touch = this.inputs.attached["touch"];
  69446. if (touch)
  69447. return touch.touchAngularSensibility;
  69448. return 0;
  69449. },
  69450. set: function (value) {
  69451. var touch = this.inputs.attached["touch"];
  69452. if (touch)
  69453. touch.touchAngularSensibility = value;
  69454. },
  69455. enumerable: true,
  69456. configurable: true
  69457. });
  69458. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69459. get: function () {
  69460. var touch = this.inputs.attached["touch"];
  69461. if (touch)
  69462. return touch.touchMoveSensibility;
  69463. return 0;
  69464. },
  69465. set: function (value) {
  69466. var touch = this.inputs.attached["touch"];
  69467. if (touch)
  69468. touch.touchMoveSensibility = value;
  69469. },
  69470. enumerable: true,
  69471. configurable: true
  69472. });
  69473. TouchCamera.prototype.getClassName = function () {
  69474. return "TouchCamera";
  69475. };
  69476. TouchCamera.prototype._setupInputs = function () {
  69477. var mouse = this.inputs.attached["mouse"];
  69478. if (mouse) {
  69479. mouse.touchEnabled = false;
  69480. }
  69481. };
  69482. return TouchCamera;
  69483. }(BABYLON.FreeCamera));
  69484. BABYLON.TouchCamera = TouchCamera;
  69485. })(BABYLON || (BABYLON = {}));
  69486. //# sourceMappingURL=babylon.touchCamera.js.map
  69487. var BABYLON;
  69488. (function (BABYLON) {
  69489. var ProceduralTexture = /** @class */ (function (_super) {
  69490. __extends(ProceduralTexture, _super);
  69491. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69492. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69493. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69494. if (isCube === void 0) { isCube = false; }
  69495. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69496. _this.isCube = isCube;
  69497. _this.isEnabled = true;
  69498. _this._currentRefreshId = -1;
  69499. _this._refreshRate = 1;
  69500. _this._vertexBuffers = {};
  69501. _this._uniforms = new Array();
  69502. _this._samplers = new Array();
  69503. _this._textures = {};
  69504. _this._floats = {};
  69505. _this._floatsArrays = {};
  69506. _this._colors3 = {};
  69507. _this._colors4 = {};
  69508. _this._vectors2 = {};
  69509. _this._vectors3 = {};
  69510. _this._matrices = {};
  69511. _this._fallbackTextureUsed = false;
  69512. scene.proceduralTextures.push(_this);
  69513. _this._engine = scene.getEngine();
  69514. _this.name = name;
  69515. _this.isRenderTarget = true;
  69516. _this._size = size;
  69517. _this._generateMipMaps = generateMipMaps;
  69518. _this.setFragment(fragment);
  69519. _this._fallbackTexture = fallbackTexture;
  69520. if (isCube) {
  69521. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69522. _this.setFloat("face", 0);
  69523. }
  69524. else {
  69525. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69526. }
  69527. // VBO
  69528. var vertices = [];
  69529. vertices.push(1, 1);
  69530. vertices.push(-1, 1);
  69531. vertices.push(-1, -1);
  69532. vertices.push(1, -1);
  69533. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69534. _this._createIndexBuffer();
  69535. return _this;
  69536. }
  69537. ProceduralTexture.prototype._createIndexBuffer = function () {
  69538. var engine = this._engine;
  69539. // Indices
  69540. var indices = [];
  69541. indices.push(0);
  69542. indices.push(1);
  69543. indices.push(2);
  69544. indices.push(0);
  69545. indices.push(2);
  69546. indices.push(3);
  69547. this._indexBuffer = engine.createIndexBuffer(indices);
  69548. };
  69549. ProceduralTexture.prototype._rebuild = function () {
  69550. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69551. if (vb) {
  69552. vb._rebuild();
  69553. }
  69554. this._createIndexBuffer();
  69555. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69556. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69557. }
  69558. };
  69559. ProceduralTexture.prototype.reset = function () {
  69560. if (this._effect === undefined) {
  69561. return;
  69562. }
  69563. var engine = this._engine;
  69564. engine._releaseEffect(this._effect);
  69565. };
  69566. ProceduralTexture.prototype.isReady = function () {
  69567. var _this = this;
  69568. var engine = this._engine;
  69569. var shaders;
  69570. if (!this._fragment) {
  69571. return false;
  69572. }
  69573. if (this._fallbackTextureUsed) {
  69574. return true;
  69575. }
  69576. if (this._fragment.fragmentElement !== undefined) {
  69577. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69578. }
  69579. else {
  69580. shaders = { vertex: "procedural", fragment: this._fragment };
  69581. }
  69582. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69583. _this.releaseInternalTexture();
  69584. if (_this._fallbackTexture) {
  69585. _this._texture = _this._fallbackTexture._texture;
  69586. if (_this._texture) {
  69587. _this._texture.incrementReferences();
  69588. }
  69589. }
  69590. _this._fallbackTextureUsed = true;
  69591. });
  69592. return this._effect.isReady();
  69593. };
  69594. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69595. this._currentRefreshId = -1;
  69596. };
  69597. ProceduralTexture.prototype.setFragment = function (fragment) {
  69598. this._fragment = fragment;
  69599. };
  69600. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69601. get: function () {
  69602. return this._refreshRate;
  69603. },
  69604. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69605. set: function (value) {
  69606. this._refreshRate = value;
  69607. this.resetRefreshCounter();
  69608. },
  69609. enumerable: true,
  69610. configurable: true
  69611. });
  69612. ProceduralTexture.prototype._shouldRender = function () {
  69613. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69614. return false;
  69615. }
  69616. if (this._fallbackTextureUsed) {
  69617. return false;
  69618. }
  69619. if (this._currentRefreshId === -1) { // At least render once
  69620. this._currentRefreshId = 1;
  69621. return true;
  69622. }
  69623. if (this.refreshRate === this._currentRefreshId) {
  69624. this._currentRefreshId = 1;
  69625. return true;
  69626. }
  69627. this._currentRefreshId++;
  69628. return false;
  69629. };
  69630. ProceduralTexture.prototype.getRenderSize = function () {
  69631. return this._size;
  69632. };
  69633. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69634. if (this._fallbackTextureUsed) {
  69635. return;
  69636. }
  69637. this.releaseInternalTexture();
  69638. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69639. };
  69640. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69641. if (this._uniforms.indexOf(uniformName) === -1) {
  69642. this._uniforms.push(uniformName);
  69643. }
  69644. };
  69645. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69646. if (this._samplers.indexOf(name) === -1) {
  69647. this._samplers.push(name);
  69648. }
  69649. this._textures[name] = texture;
  69650. return this;
  69651. };
  69652. ProceduralTexture.prototype.setFloat = function (name, value) {
  69653. this._checkUniform(name);
  69654. this._floats[name] = value;
  69655. return this;
  69656. };
  69657. ProceduralTexture.prototype.setFloats = function (name, value) {
  69658. this._checkUniform(name);
  69659. this._floatsArrays[name] = value;
  69660. return this;
  69661. };
  69662. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69663. this._checkUniform(name);
  69664. this._colors3[name] = value;
  69665. return this;
  69666. };
  69667. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69668. this._checkUniform(name);
  69669. this._colors4[name] = value;
  69670. return this;
  69671. };
  69672. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69673. this._checkUniform(name);
  69674. this._vectors2[name] = value;
  69675. return this;
  69676. };
  69677. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69678. this._checkUniform(name);
  69679. this._vectors3[name] = value;
  69680. return this;
  69681. };
  69682. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69683. this._checkUniform(name);
  69684. this._matrices[name] = value;
  69685. return this;
  69686. };
  69687. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69688. var scene = this.getScene();
  69689. if (!scene) {
  69690. return;
  69691. }
  69692. var engine = this._engine;
  69693. // Render
  69694. engine.enableEffect(this._effect);
  69695. engine.setState(false);
  69696. // Texture
  69697. for (var name in this._textures) {
  69698. this._effect.setTexture(name, this._textures[name]);
  69699. }
  69700. // Float
  69701. for (name in this._floats) {
  69702. this._effect.setFloat(name, this._floats[name]);
  69703. }
  69704. // Floats
  69705. for (name in this._floatsArrays) {
  69706. this._effect.setArray(name, this._floatsArrays[name]);
  69707. }
  69708. // Color3
  69709. for (name in this._colors3) {
  69710. this._effect.setColor3(name, this._colors3[name]);
  69711. }
  69712. // Color4
  69713. for (name in this._colors4) {
  69714. var color = this._colors4[name];
  69715. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69716. }
  69717. // Vector2
  69718. for (name in this._vectors2) {
  69719. this._effect.setVector2(name, this._vectors2[name]);
  69720. }
  69721. // Vector3
  69722. for (name in this._vectors3) {
  69723. this._effect.setVector3(name, this._vectors3[name]);
  69724. }
  69725. // Matrix
  69726. for (name in this._matrices) {
  69727. this._effect.setMatrix(name, this._matrices[name]);
  69728. }
  69729. if (!this._texture) {
  69730. return;
  69731. }
  69732. if (this.isCube) {
  69733. for (var face = 0; face < 6; face++) {
  69734. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69735. // VBOs
  69736. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69737. this._effect.setFloat("face", face);
  69738. // Clear
  69739. engine.clear(scene.clearColor, true, true, true);
  69740. // Draw order
  69741. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69742. // Mipmaps
  69743. if (face === 5) {
  69744. engine.generateMipMapsForCubemap(this._texture);
  69745. }
  69746. }
  69747. }
  69748. else {
  69749. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69750. // VBOs
  69751. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69752. // Clear
  69753. engine.clear(scene.clearColor, true, true, true);
  69754. // Draw order
  69755. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69756. }
  69757. // Unbind
  69758. engine.unBindFramebuffer(this._texture, this.isCube);
  69759. if (this.onGenerated) {
  69760. this.onGenerated();
  69761. }
  69762. };
  69763. ProceduralTexture.prototype.clone = function () {
  69764. var textureSize = this.getSize();
  69765. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69766. // Base texture
  69767. newTexture.hasAlpha = this.hasAlpha;
  69768. newTexture.level = this.level;
  69769. // RenderTarget Texture
  69770. newTexture.coordinatesMode = this.coordinatesMode;
  69771. return newTexture;
  69772. };
  69773. ProceduralTexture.prototype.dispose = function () {
  69774. var scene = this.getScene();
  69775. if (!scene) {
  69776. return;
  69777. }
  69778. var index = scene.proceduralTextures.indexOf(this);
  69779. if (index >= 0) {
  69780. scene.proceduralTextures.splice(index, 1);
  69781. }
  69782. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69783. if (vertexBuffer) {
  69784. vertexBuffer.dispose();
  69785. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69786. }
  69787. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69788. this._indexBuffer = null;
  69789. }
  69790. _super.prototype.dispose.call(this);
  69791. };
  69792. return ProceduralTexture;
  69793. }(BABYLON.Texture));
  69794. BABYLON.ProceduralTexture = ProceduralTexture;
  69795. })(BABYLON || (BABYLON = {}));
  69796. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69797. var BABYLON;
  69798. (function (BABYLON) {
  69799. var CustomProceduralTexture = /** @class */ (function (_super) {
  69800. __extends(CustomProceduralTexture, _super);
  69801. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69802. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69803. _this._animate = true;
  69804. _this._time = 0;
  69805. _this._texturePath = texturePath;
  69806. //Try to load json
  69807. _this.loadJson(texturePath);
  69808. _this.refreshRate = 1;
  69809. return _this;
  69810. }
  69811. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69812. var _this = this;
  69813. var noConfigFile = function () {
  69814. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69815. try {
  69816. _this.setFragment(_this._texturePath);
  69817. }
  69818. catch (ex) {
  69819. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69820. }
  69821. };
  69822. var configFileUrl = jsonUrl + "/config.json";
  69823. var xhr = new XMLHttpRequest();
  69824. xhr.open("GET", configFileUrl, true);
  69825. xhr.addEventListener("load", function () {
  69826. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69827. try {
  69828. _this._config = JSON.parse(xhr.response);
  69829. _this.updateShaderUniforms();
  69830. _this.updateTextures();
  69831. _this.setFragment(_this._texturePath + "/custom");
  69832. _this._animate = _this._config.animate;
  69833. _this.refreshRate = _this._config.refreshrate;
  69834. }
  69835. catch (ex) {
  69836. noConfigFile();
  69837. }
  69838. }
  69839. else {
  69840. noConfigFile();
  69841. }
  69842. }, false);
  69843. xhr.addEventListener("error", function () {
  69844. noConfigFile();
  69845. }, false);
  69846. try {
  69847. xhr.send();
  69848. }
  69849. catch (ex) {
  69850. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69851. }
  69852. };
  69853. CustomProceduralTexture.prototype.isReady = function () {
  69854. if (!_super.prototype.isReady.call(this)) {
  69855. return false;
  69856. }
  69857. for (var name in this._textures) {
  69858. var texture = this._textures[name];
  69859. if (!texture.isReady()) {
  69860. return false;
  69861. }
  69862. }
  69863. return true;
  69864. };
  69865. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69866. var scene = this.getScene();
  69867. if (this._animate && scene) {
  69868. this._time += scene.getAnimationRatio() * 0.03;
  69869. this.updateShaderUniforms();
  69870. }
  69871. _super.prototype.render.call(this, useCameraPostProcess);
  69872. };
  69873. CustomProceduralTexture.prototype.updateTextures = function () {
  69874. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69875. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69876. }
  69877. };
  69878. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69879. if (this._config) {
  69880. for (var j = 0; j < this._config.uniforms.length; j++) {
  69881. var uniform = this._config.uniforms[j];
  69882. switch (uniform.type) {
  69883. case "float":
  69884. this.setFloat(uniform.name, uniform.value);
  69885. break;
  69886. case "color3":
  69887. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69888. break;
  69889. case "color4":
  69890. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69891. break;
  69892. case "vector2":
  69893. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69894. break;
  69895. case "vector3":
  69896. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69897. break;
  69898. }
  69899. }
  69900. }
  69901. this.setFloat("time", this._time);
  69902. };
  69903. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69904. get: function () {
  69905. return this._animate;
  69906. },
  69907. set: function (value) {
  69908. this._animate = value;
  69909. },
  69910. enumerable: true,
  69911. configurable: true
  69912. });
  69913. return CustomProceduralTexture;
  69914. }(BABYLON.ProceduralTexture));
  69915. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69916. })(BABYLON || (BABYLON = {}));
  69917. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69918. var BABYLON;
  69919. (function (BABYLON) {
  69920. var FreeCameraGamepadInput = /** @class */ (function () {
  69921. function FreeCameraGamepadInput() {
  69922. this.gamepadAngularSensibility = 200;
  69923. this.gamepadMoveSensibility = 40;
  69924. // private members
  69925. this._cameraTransform = BABYLON.Matrix.Identity();
  69926. this._deltaTransform = BABYLON.Vector3.Zero();
  69927. this._vector3 = BABYLON.Vector3.Zero();
  69928. this._vector2 = BABYLON.Vector2.Zero();
  69929. }
  69930. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69931. var _this = this;
  69932. var manager = this.camera.getScene().gamepadManager;
  69933. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69934. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69935. // prioritize XBOX gamepads.
  69936. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69937. _this.gamepad = gamepad;
  69938. }
  69939. }
  69940. });
  69941. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69942. if (_this.gamepad === gamepad) {
  69943. _this.gamepad = null;
  69944. }
  69945. });
  69946. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69947. };
  69948. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69949. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69950. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69951. this.gamepad = null;
  69952. };
  69953. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69954. if (this.gamepad && this.gamepad.leftStick) {
  69955. var camera = this.camera;
  69956. var LSValues = this.gamepad.leftStick;
  69957. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69958. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69959. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69960. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69961. var RSValues = this.gamepad.rightStick;
  69962. if (RSValues) {
  69963. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69964. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69965. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69966. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69967. }
  69968. else {
  69969. RSValues = { x: 0, y: 0 };
  69970. }
  69971. if (!camera.rotationQuaternion) {
  69972. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69973. }
  69974. else {
  69975. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69976. }
  69977. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69978. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69979. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69980. camera.cameraDirection.addInPlace(this._deltaTransform);
  69981. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69982. camera.cameraRotation.addInPlace(this._vector2);
  69983. }
  69984. };
  69985. FreeCameraGamepadInput.prototype.getClassName = function () {
  69986. return "FreeCameraGamepadInput";
  69987. };
  69988. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69989. return "gamepad";
  69990. };
  69991. __decorate([
  69992. BABYLON.serialize()
  69993. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69994. __decorate([
  69995. BABYLON.serialize()
  69996. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69997. return FreeCameraGamepadInput;
  69998. }());
  69999. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70000. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70001. })(BABYLON || (BABYLON = {}));
  70002. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70003. var BABYLON;
  70004. (function (BABYLON) {
  70005. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70006. function ArcRotateCameraGamepadInput() {
  70007. this.gamepadRotationSensibility = 80;
  70008. this.gamepadMoveSensibility = 40;
  70009. }
  70010. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70011. var _this = this;
  70012. var manager = this.camera.getScene().gamepadManager;
  70013. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70014. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70015. // prioritize XBOX gamepads.
  70016. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70017. _this.gamepad = gamepad;
  70018. }
  70019. }
  70020. });
  70021. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70022. if (_this.gamepad === gamepad) {
  70023. _this.gamepad = null;
  70024. }
  70025. });
  70026. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70027. };
  70028. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70029. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70030. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70031. this.gamepad = null;
  70032. };
  70033. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70034. if (this.gamepad) {
  70035. var camera = this.camera;
  70036. var RSValues = this.gamepad.rightStick;
  70037. if (RSValues) {
  70038. if (RSValues.x != 0) {
  70039. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70040. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70041. camera.inertialAlphaOffset += normalizedRX;
  70042. }
  70043. }
  70044. if (RSValues.y != 0) {
  70045. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70046. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70047. camera.inertialBetaOffset += normalizedRY;
  70048. }
  70049. }
  70050. }
  70051. var LSValues = this.gamepad.leftStick;
  70052. if (LSValues && LSValues.y != 0) {
  70053. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70054. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70055. this.camera.inertialRadiusOffset -= normalizedLY;
  70056. }
  70057. }
  70058. }
  70059. };
  70060. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70061. return "ArcRotateCameraGamepadInput";
  70062. };
  70063. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70064. return "gamepad";
  70065. };
  70066. __decorate([
  70067. BABYLON.serialize()
  70068. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70069. __decorate([
  70070. BABYLON.serialize()
  70071. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70072. return ArcRotateCameraGamepadInput;
  70073. }());
  70074. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70075. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70076. })(BABYLON || (BABYLON = {}));
  70077. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70078. var BABYLON;
  70079. (function (BABYLON) {
  70080. var GamepadManager = /** @class */ (function () {
  70081. function GamepadManager(_scene) {
  70082. var _this = this;
  70083. this._scene = _scene;
  70084. this._babylonGamepads = [];
  70085. this._oneGamepadConnected = false;
  70086. this._isMonitoring = false;
  70087. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70088. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70089. this._gamepadEventSupported = false;
  70090. }
  70091. else {
  70092. this._gamepadEventSupported = 'GamepadEvent' in window;
  70093. this._gamepadSupport = (navigator.getGamepads ||
  70094. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70095. }
  70096. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70097. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70098. for (var i in _this._babylonGamepads) {
  70099. var gamepad = _this._babylonGamepads[i];
  70100. if (gamepad && gamepad._isConnected) {
  70101. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70102. }
  70103. }
  70104. });
  70105. this._onGamepadConnectedEvent = function (evt) {
  70106. var gamepad = evt.gamepad;
  70107. if (gamepad.index in _this._babylonGamepads) {
  70108. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70109. return;
  70110. }
  70111. }
  70112. var newGamepad;
  70113. if (_this._babylonGamepads[gamepad.index]) {
  70114. newGamepad = _this._babylonGamepads[gamepad.index];
  70115. newGamepad.browserGamepad = gamepad;
  70116. newGamepad._isConnected = true;
  70117. }
  70118. else {
  70119. newGamepad = _this._addNewGamepad(gamepad);
  70120. }
  70121. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70122. _this._startMonitoringGamepads();
  70123. };
  70124. this._onGamepadDisconnectedEvent = function (evt) {
  70125. var gamepad = evt.gamepad;
  70126. // Remove the gamepad from the list of gamepads to monitor.
  70127. for (var i in _this._babylonGamepads) {
  70128. if (_this._babylonGamepads[i].index === gamepad.index) {
  70129. var disconnectedGamepad = _this._babylonGamepads[i];
  70130. disconnectedGamepad._isConnected = false;
  70131. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70132. break;
  70133. }
  70134. }
  70135. };
  70136. if (this._gamepadSupport) {
  70137. //first add already-connected gamepads
  70138. this._updateGamepadObjects();
  70139. if (this._babylonGamepads.length) {
  70140. this._startMonitoringGamepads();
  70141. }
  70142. // Checking if the gamepad connected event is supported (like in Firefox)
  70143. if (this._gamepadEventSupported) {
  70144. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70145. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70146. }
  70147. else {
  70148. this._startMonitoringGamepads();
  70149. }
  70150. }
  70151. }
  70152. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70153. get: function () {
  70154. return this._babylonGamepads;
  70155. },
  70156. enumerable: true,
  70157. configurable: true
  70158. });
  70159. GamepadManager.prototype.getGamepadByType = function (type) {
  70160. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70161. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70162. var gamepad = _a[_i];
  70163. if (gamepad && gamepad.type === type) {
  70164. return gamepad;
  70165. }
  70166. }
  70167. return null;
  70168. };
  70169. GamepadManager.prototype.dispose = function () {
  70170. if (this._gamepadEventSupported) {
  70171. if (this._onGamepadConnectedEvent) {
  70172. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70173. }
  70174. if (this._onGamepadDisconnectedEvent) {
  70175. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70176. }
  70177. this._onGamepadConnectedEvent = null;
  70178. this._onGamepadDisconnectedEvent = null;
  70179. }
  70180. this._babylonGamepads.forEach(function (gamepad) {
  70181. gamepad.dispose();
  70182. });
  70183. this.onGamepadConnectedObservable.clear();
  70184. this.onGamepadDisconnectedObservable.clear();
  70185. this._oneGamepadConnected = false;
  70186. this._stopMonitoringGamepads();
  70187. this._babylonGamepads = [];
  70188. };
  70189. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70190. if (!this._oneGamepadConnected) {
  70191. this._oneGamepadConnected = true;
  70192. }
  70193. var newGamepad;
  70194. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70195. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70196. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70197. }
  70198. // if pose is supported, use the (WebVR) pose enabled controller
  70199. else if (gamepad.pose) {
  70200. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70201. }
  70202. else {
  70203. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70204. }
  70205. this._babylonGamepads[newGamepad.index] = newGamepad;
  70206. return newGamepad;
  70207. };
  70208. GamepadManager.prototype._startMonitoringGamepads = function () {
  70209. if (!this._isMonitoring) {
  70210. this._isMonitoring = true;
  70211. //back-comp
  70212. if (!this._scene) {
  70213. this._checkGamepadsStatus();
  70214. }
  70215. }
  70216. };
  70217. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70218. this._isMonitoring = false;
  70219. };
  70220. GamepadManager.prototype._checkGamepadsStatus = function () {
  70221. var _this = this;
  70222. // Hack to be compatible Chrome
  70223. this._updateGamepadObjects();
  70224. for (var i in this._babylonGamepads) {
  70225. var gamepad = this._babylonGamepads[i];
  70226. if (!gamepad || !gamepad.isConnected) {
  70227. continue;
  70228. }
  70229. gamepad.update();
  70230. }
  70231. if (this._isMonitoring && !this._scene) {
  70232. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70233. }
  70234. };
  70235. // This function is called only on Chrome, which does not properly support
  70236. // connection/disconnection events and forces you to recopy again the gamepad object
  70237. GamepadManager.prototype._updateGamepadObjects = function () {
  70238. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70239. for (var i = 0; i < gamepads.length; i++) {
  70240. var gamepad = gamepads[i];
  70241. if (gamepad) {
  70242. if (!this._babylonGamepads[gamepad.index]) {
  70243. var newGamepad = this._addNewGamepad(gamepad);
  70244. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70245. }
  70246. else {
  70247. // Forced to copy again this object for Chrome for unknown reason
  70248. this._babylonGamepads[i].browserGamepad = gamepad;
  70249. if (!this._babylonGamepads[i].isConnected) {
  70250. this._babylonGamepads[i]._isConnected = true;
  70251. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70252. }
  70253. }
  70254. }
  70255. }
  70256. };
  70257. return GamepadManager;
  70258. }());
  70259. BABYLON.GamepadManager = GamepadManager;
  70260. })(BABYLON || (BABYLON = {}));
  70261. //# sourceMappingURL=babylon.gamepadManager.js.map
  70262. var BABYLON;
  70263. (function (BABYLON) {
  70264. var StickValues = /** @class */ (function () {
  70265. function StickValues(x, y) {
  70266. this.x = x;
  70267. this.y = y;
  70268. }
  70269. return StickValues;
  70270. }());
  70271. BABYLON.StickValues = StickValues;
  70272. var Gamepad = /** @class */ (function () {
  70273. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70274. if (leftStickX === void 0) { leftStickX = 0; }
  70275. if (leftStickY === void 0) { leftStickY = 1; }
  70276. if (rightStickX === void 0) { rightStickX = 2; }
  70277. if (rightStickY === void 0) { rightStickY = 3; }
  70278. this.id = id;
  70279. this.index = index;
  70280. this.browserGamepad = browserGamepad;
  70281. this._isConnected = true;
  70282. this._invertLeftStickY = false;
  70283. this.type = Gamepad.GAMEPAD;
  70284. this._leftStickAxisX = leftStickX;
  70285. this._leftStickAxisY = leftStickY;
  70286. this._rightStickAxisX = rightStickX;
  70287. this._rightStickAxisY = rightStickY;
  70288. if (this.browserGamepad.axes.length >= 2) {
  70289. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70290. }
  70291. if (this.browserGamepad.axes.length >= 4) {
  70292. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70293. }
  70294. }
  70295. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70296. get: function () {
  70297. return this._isConnected;
  70298. },
  70299. enumerable: true,
  70300. configurable: true
  70301. });
  70302. Gamepad.prototype.onleftstickchanged = function (callback) {
  70303. this._onleftstickchanged = callback;
  70304. };
  70305. Gamepad.prototype.onrightstickchanged = function (callback) {
  70306. this._onrightstickchanged = callback;
  70307. };
  70308. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70309. get: function () {
  70310. return this._leftStick;
  70311. },
  70312. set: function (newValues) {
  70313. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70314. this._onleftstickchanged(newValues);
  70315. }
  70316. this._leftStick = newValues;
  70317. },
  70318. enumerable: true,
  70319. configurable: true
  70320. });
  70321. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70322. get: function () {
  70323. return this._rightStick;
  70324. },
  70325. set: function (newValues) {
  70326. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70327. this._onrightstickchanged(newValues);
  70328. }
  70329. this._rightStick = newValues;
  70330. },
  70331. enumerable: true,
  70332. configurable: true
  70333. });
  70334. Gamepad.prototype.update = function () {
  70335. if (this._leftStick) {
  70336. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70337. if (this._invertLeftStickY) {
  70338. this.leftStick.y *= -1;
  70339. }
  70340. }
  70341. if (this._rightStick) {
  70342. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70343. }
  70344. };
  70345. Gamepad.prototype.dispose = function () {
  70346. };
  70347. Gamepad.GAMEPAD = 0;
  70348. Gamepad.GENERIC = 1;
  70349. Gamepad.XBOX = 2;
  70350. Gamepad.POSE_ENABLED = 3;
  70351. return Gamepad;
  70352. }());
  70353. BABYLON.Gamepad = Gamepad;
  70354. var GenericPad = /** @class */ (function (_super) {
  70355. __extends(GenericPad, _super);
  70356. function GenericPad(id, index, browserGamepad) {
  70357. var _this = _super.call(this, id, index, browserGamepad) || this;
  70358. _this.onButtonDownObservable = new BABYLON.Observable();
  70359. _this.onButtonUpObservable = new BABYLON.Observable();
  70360. _this.type = Gamepad.GENERIC;
  70361. _this._buttons = new Array(browserGamepad.buttons.length);
  70362. return _this;
  70363. }
  70364. GenericPad.prototype.onbuttondown = function (callback) {
  70365. this._onbuttondown = callback;
  70366. };
  70367. GenericPad.prototype.onbuttonup = function (callback) {
  70368. this._onbuttonup = callback;
  70369. };
  70370. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70371. if (newValue !== currentValue) {
  70372. if (newValue === 1) {
  70373. if (this._onbuttondown) {
  70374. this._onbuttondown(buttonIndex);
  70375. }
  70376. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70377. }
  70378. if (newValue === 0) {
  70379. if (this._onbuttonup) {
  70380. this._onbuttonup(buttonIndex);
  70381. }
  70382. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70383. }
  70384. }
  70385. return newValue;
  70386. };
  70387. GenericPad.prototype.update = function () {
  70388. _super.prototype.update.call(this);
  70389. for (var index = 0; index < this._buttons.length; index++) {
  70390. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70391. }
  70392. };
  70393. GenericPad.prototype.dispose = function () {
  70394. _super.prototype.dispose.call(this);
  70395. this.onButtonDownObservable.clear();
  70396. this.onButtonUpObservable.clear();
  70397. };
  70398. return GenericPad;
  70399. }(Gamepad));
  70400. BABYLON.GenericPad = GenericPad;
  70401. })(BABYLON || (BABYLON = {}));
  70402. //# sourceMappingURL=babylon.gamepad.js.map
  70403. var BABYLON;
  70404. (function (BABYLON) {
  70405. /**
  70406. * Defines supported buttons for XBox360 compatible gamepads
  70407. */
  70408. var Xbox360Button;
  70409. (function (Xbox360Button) {
  70410. /** A */
  70411. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70412. /** B */
  70413. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70414. /** X */
  70415. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70416. /** Y */
  70417. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70418. /** Start */
  70419. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70420. /** Back */
  70421. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70422. /** Left button */
  70423. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70424. /** Right button */
  70425. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70426. /** Left stick */
  70427. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70428. /** Right stick */
  70429. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70430. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70431. /** Defines values for XBox360 DPad */
  70432. var Xbox360Dpad;
  70433. (function (Xbox360Dpad) {
  70434. /** Up */
  70435. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70436. /** Down */
  70437. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70438. /** Left */
  70439. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70440. /** Right */
  70441. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70442. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70443. /**
  70444. * Defines a XBox360 gamepad
  70445. */
  70446. var Xbox360Pad = /** @class */ (function (_super) {
  70447. __extends(Xbox360Pad, _super);
  70448. /**
  70449. * Creates a new XBox360 gamepad object
  70450. * @param id defines the id of this gamepad
  70451. * @param index defines its index
  70452. * @param gamepad defines the internal HTML gamepad object
  70453. * @param xboxOne defines if it is a XBox One gamepad
  70454. */
  70455. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70456. if (xboxOne === void 0) { xboxOne = false; }
  70457. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70458. _this._leftTrigger = 0;
  70459. _this._rightTrigger = 0;
  70460. /** Observable raised when a button is pressed */
  70461. _this.onButtonDownObservable = new BABYLON.Observable();
  70462. /** Observable raised when a button is released */
  70463. _this.onButtonUpObservable = new BABYLON.Observable();
  70464. /** Observable raised when a pad is pressed */
  70465. _this.onPadDownObservable = new BABYLON.Observable();
  70466. /** Observable raised when a pad is released */
  70467. _this.onPadUpObservable = new BABYLON.Observable();
  70468. _this._buttonA = 0;
  70469. _this._buttonB = 0;
  70470. _this._buttonX = 0;
  70471. _this._buttonY = 0;
  70472. _this._buttonBack = 0;
  70473. _this._buttonStart = 0;
  70474. _this._buttonLB = 0;
  70475. _this._buttonRB = 0;
  70476. _this._buttonLeftStick = 0;
  70477. _this._buttonRightStick = 0;
  70478. _this._dPadUp = 0;
  70479. _this._dPadDown = 0;
  70480. _this._dPadLeft = 0;
  70481. _this._dPadRight = 0;
  70482. _this._isXboxOnePad = false;
  70483. _this.type = BABYLON.Gamepad.XBOX;
  70484. _this._isXboxOnePad = xboxOne;
  70485. return _this;
  70486. }
  70487. /**
  70488. * Defines the callback to call when left trigger is pressed
  70489. * @param callback defines the callback to use
  70490. */
  70491. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70492. this._onlefttriggerchanged = callback;
  70493. };
  70494. /**
  70495. * Defines the callback to call when right trigger is pressed
  70496. * @param callback defines the callback to use
  70497. */
  70498. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70499. this._onrighttriggerchanged = callback;
  70500. };
  70501. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70502. /**
  70503. * Gets or sets left trigger value
  70504. */
  70505. get: function () {
  70506. return this._leftTrigger;
  70507. },
  70508. set: function (newValue) {
  70509. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70510. this._onlefttriggerchanged(newValue);
  70511. }
  70512. this._leftTrigger = newValue;
  70513. },
  70514. enumerable: true,
  70515. configurable: true
  70516. });
  70517. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70518. /**
  70519. * Gets or sets right trigger value
  70520. */
  70521. get: function () {
  70522. return this._rightTrigger;
  70523. },
  70524. set: function (newValue) {
  70525. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70526. this._onrighttriggerchanged(newValue);
  70527. }
  70528. this._rightTrigger = newValue;
  70529. },
  70530. enumerable: true,
  70531. configurable: true
  70532. });
  70533. /**
  70534. * Defines the callback to call when a button is pressed
  70535. * @param callback defines the callback to use
  70536. */
  70537. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70538. this._onbuttondown = callback;
  70539. };
  70540. /**
  70541. * Defines the callback to call when a button is released
  70542. * @param callback defines the callback to use
  70543. */
  70544. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70545. this._onbuttonup = callback;
  70546. };
  70547. /**
  70548. * Defines the callback to call when a pad is pressed
  70549. * @param callback defines the callback to use
  70550. */
  70551. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70552. this._ondpaddown = callback;
  70553. };
  70554. /**
  70555. * Defines the callback to call when a pad is released
  70556. * @param callback defines the callback to use
  70557. */
  70558. Xbox360Pad.prototype.ondpadup = function (callback) {
  70559. this._ondpadup = callback;
  70560. };
  70561. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70562. if (newValue !== currentValue) {
  70563. if (newValue === 1) {
  70564. if (this._onbuttondown) {
  70565. this._onbuttondown(buttonType);
  70566. }
  70567. this.onButtonDownObservable.notifyObservers(buttonType);
  70568. }
  70569. if (newValue === 0) {
  70570. if (this._onbuttonup) {
  70571. this._onbuttonup(buttonType);
  70572. }
  70573. this.onButtonUpObservable.notifyObservers(buttonType);
  70574. }
  70575. }
  70576. return newValue;
  70577. };
  70578. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70579. if (newValue !== currentValue) {
  70580. if (newValue === 1) {
  70581. if (this._ondpaddown) {
  70582. this._ondpaddown(buttonType);
  70583. }
  70584. this.onPadDownObservable.notifyObservers(buttonType);
  70585. }
  70586. if (newValue === 0) {
  70587. if (this._ondpadup) {
  70588. this._ondpadup(buttonType);
  70589. }
  70590. this.onPadUpObservable.notifyObservers(buttonType);
  70591. }
  70592. }
  70593. return newValue;
  70594. };
  70595. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70596. /** Gets or sets value of A button */
  70597. get: function () {
  70598. return this._buttonA;
  70599. },
  70600. set: function (value) {
  70601. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70602. },
  70603. enumerable: true,
  70604. configurable: true
  70605. });
  70606. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70607. /** Gets or sets value of B button */
  70608. get: function () {
  70609. return this._buttonB;
  70610. },
  70611. set: function (value) {
  70612. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70613. },
  70614. enumerable: true,
  70615. configurable: true
  70616. });
  70617. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70618. /** Gets or sets value of X button */
  70619. get: function () {
  70620. return this._buttonX;
  70621. },
  70622. set: function (value) {
  70623. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70624. },
  70625. enumerable: true,
  70626. configurable: true
  70627. });
  70628. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70629. /** Gets or sets value of Y button */
  70630. get: function () {
  70631. return this._buttonY;
  70632. },
  70633. set: function (value) {
  70634. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70635. },
  70636. enumerable: true,
  70637. configurable: true
  70638. });
  70639. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70640. /** Gets or sets value of Start button */
  70641. get: function () {
  70642. return this._buttonStart;
  70643. },
  70644. set: function (value) {
  70645. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70646. },
  70647. enumerable: true,
  70648. configurable: true
  70649. });
  70650. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70651. /** Gets or sets value of Back button */
  70652. get: function () {
  70653. return this._buttonBack;
  70654. },
  70655. set: function (value) {
  70656. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70657. },
  70658. enumerable: true,
  70659. configurable: true
  70660. });
  70661. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70662. /** Gets or sets value of Left button */
  70663. get: function () {
  70664. return this._buttonLB;
  70665. },
  70666. set: function (value) {
  70667. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70668. },
  70669. enumerable: true,
  70670. configurable: true
  70671. });
  70672. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70673. /** Gets or sets value of Right button */
  70674. get: function () {
  70675. return this._buttonRB;
  70676. },
  70677. set: function (value) {
  70678. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70679. },
  70680. enumerable: true,
  70681. configurable: true
  70682. });
  70683. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70684. /** Gets or sets value of left stick */
  70685. get: function () {
  70686. return this._buttonLeftStick;
  70687. },
  70688. set: function (value) {
  70689. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70690. },
  70691. enumerable: true,
  70692. configurable: true
  70693. });
  70694. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70695. /** Gets or sets value of right stick */
  70696. get: function () {
  70697. return this._buttonRightStick;
  70698. },
  70699. set: function (value) {
  70700. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70701. },
  70702. enumerable: true,
  70703. configurable: true
  70704. });
  70705. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70706. /** Gets or sets value of DPad up */
  70707. get: function () {
  70708. return this._dPadUp;
  70709. },
  70710. set: function (value) {
  70711. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70712. },
  70713. enumerable: true,
  70714. configurable: true
  70715. });
  70716. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70717. /** Gets or sets value of DPad down */
  70718. get: function () {
  70719. return this._dPadDown;
  70720. },
  70721. set: function (value) {
  70722. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70723. },
  70724. enumerable: true,
  70725. configurable: true
  70726. });
  70727. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70728. /** Gets or sets value of DPad left */
  70729. get: function () {
  70730. return this._dPadLeft;
  70731. },
  70732. set: function (value) {
  70733. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70734. },
  70735. enumerable: true,
  70736. configurable: true
  70737. });
  70738. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70739. /** Gets or sets value of DPad right */
  70740. get: function () {
  70741. return this._dPadRight;
  70742. },
  70743. set: function (value) {
  70744. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70745. },
  70746. enumerable: true,
  70747. configurable: true
  70748. });
  70749. /**
  70750. * Force the gamepad to synchronize with device values
  70751. */
  70752. Xbox360Pad.prototype.update = function () {
  70753. _super.prototype.update.call(this);
  70754. if (this._isXboxOnePad) {
  70755. this.buttonA = this.browserGamepad.buttons[0].value;
  70756. this.buttonB = this.browserGamepad.buttons[1].value;
  70757. this.buttonX = this.browserGamepad.buttons[2].value;
  70758. this.buttonY = this.browserGamepad.buttons[3].value;
  70759. this.buttonLB = this.browserGamepad.buttons[4].value;
  70760. this.buttonRB = this.browserGamepad.buttons[5].value;
  70761. this.leftTrigger = this.browserGamepad.axes[2];
  70762. this.rightTrigger = this.browserGamepad.axes[5];
  70763. this.buttonBack = this.browserGamepad.buttons[9].value;
  70764. this.buttonStart = this.browserGamepad.buttons[8].value;
  70765. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70766. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70767. this.dPadUp = this.browserGamepad.buttons[11].value;
  70768. this.dPadDown = this.browserGamepad.buttons[12].value;
  70769. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70770. this.dPadRight = this.browserGamepad.buttons[14].value;
  70771. }
  70772. else {
  70773. this.buttonA = this.browserGamepad.buttons[0].value;
  70774. this.buttonB = this.browserGamepad.buttons[1].value;
  70775. this.buttonX = this.browserGamepad.buttons[2].value;
  70776. this.buttonY = this.browserGamepad.buttons[3].value;
  70777. this.buttonLB = this.browserGamepad.buttons[4].value;
  70778. this.buttonRB = this.browserGamepad.buttons[5].value;
  70779. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70780. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70781. this.buttonBack = this.browserGamepad.buttons[8].value;
  70782. this.buttonStart = this.browserGamepad.buttons[9].value;
  70783. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70784. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70785. this.dPadUp = this.browserGamepad.buttons[12].value;
  70786. this.dPadDown = this.browserGamepad.buttons[13].value;
  70787. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70788. this.dPadRight = this.browserGamepad.buttons[15].value;
  70789. }
  70790. };
  70791. Xbox360Pad.prototype.dispose = function () {
  70792. _super.prototype.dispose.call(this);
  70793. this.onButtonDownObservable.clear();
  70794. this.onButtonUpObservable.clear();
  70795. this.onPadDownObservable.clear();
  70796. this.onPadUpObservable.clear();
  70797. };
  70798. return Xbox360Pad;
  70799. }(BABYLON.Gamepad));
  70800. BABYLON.Xbox360Pad = Xbox360Pad;
  70801. })(BABYLON || (BABYLON = {}));
  70802. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70803. var BABYLON;
  70804. (function (BABYLON) {
  70805. /**
  70806. * Defines the types of pose enabled controllers that are supported
  70807. */
  70808. var PoseEnabledControllerType;
  70809. (function (PoseEnabledControllerType) {
  70810. /**
  70811. * HTC Vive
  70812. */
  70813. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70814. /**
  70815. * Oculus Rift
  70816. */
  70817. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70818. /**
  70819. * Windows mixed reality
  70820. */
  70821. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70822. /**
  70823. * Samsung gear VR
  70824. */
  70825. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70826. /**
  70827. * Google Daydream
  70828. */
  70829. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70830. /**
  70831. * Generic
  70832. */
  70833. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70834. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70835. /**
  70836. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70837. */
  70838. var PoseEnabledControllerHelper = /** @class */ (function () {
  70839. function PoseEnabledControllerHelper() {
  70840. }
  70841. /**
  70842. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70843. * @param vrGamepad the gamepad to initialized
  70844. * @returns a vr controller of the type the gamepad identified as
  70845. */
  70846. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70847. // Oculus Touch
  70848. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70849. return new BABYLON.OculusTouchController(vrGamepad);
  70850. }
  70851. // Windows Mixed Reality controllers
  70852. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70853. return new BABYLON.WindowsMotionController(vrGamepad);
  70854. }
  70855. // HTC Vive
  70856. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70857. return new BABYLON.ViveController(vrGamepad);
  70858. }
  70859. // Samsung/Oculus Gear VR
  70860. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70861. return new BABYLON.GearVRController(vrGamepad);
  70862. }
  70863. // Google Daydream
  70864. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70865. return new BABYLON.DaydreamController(vrGamepad);
  70866. }
  70867. // Generic
  70868. else {
  70869. return new BABYLON.GenericController(vrGamepad);
  70870. }
  70871. };
  70872. return PoseEnabledControllerHelper;
  70873. }());
  70874. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70875. /**
  70876. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70877. */
  70878. var PoseEnabledController = /** @class */ (function (_super) {
  70879. __extends(PoseEnabledController, _super);
  70880. /**
  70881. * Creates a new PoseEnabledController from a gamepad
  70882. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70883. */
  70884. function PoseEnabledController(browserGamepad) {
  70885. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70886. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70887. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70888. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70889. /**
  70890. * The device position in babylon space
  70891. */
  70892. _this.devicePosition = BABYLON.Vector3.Zero();
  70893. /**
  70894. * The device rotation in babylon space
  70895. */
  70896. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70897. /**
  70898. * The scale factor of the device in babylon space
  70899. */
  70900. _this.deviceScaleFactor = 1;
  70901. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70902. /**
  70903. * Internal, matrix used to convert room space to babylon space
  70904. */
  70905. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70906. /**
  70907. * Node to be used when casting a ray from the controller
  70908. */
  70909. _this._pointingPoseNode = null;
  70910. _this._workingMatrix = BABYLON.Matrix.Identity();
  70911. /**
  70912. * @hidden
  70913. */
  70914. _this._meshAttachedObservable = new BABYLON.Observable();
  70915. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70916. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70917. _this.position = BABYLON.Vector3.Zero();
  70918. _this.rotationQuaternion = new BABYLON.Quaternion();
  70919. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70920. _this._calculatedRotation = new BABYLON.Quaternion();
  70921. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70922. return _this;
  70923. }
  70924. /**
  70925. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70926. */
  70927. PoseEnabledController.prototype.update = function () {
  70928. _super.prototype.update.call(this);
  70929. var pose = this.browserGamepad.pose;
  70930. this.updateFromDevice(pose);
  70931. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70932. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70933. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70934. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70935. if (this._mesh) {
  70936. this._mesh.position.copyFrom(this.devicePosition);
  70937. if (this._mesh.rotationQuaternion) {
  70938. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70939. }
  70940. }
  70941. };
  70942. /**
  70943. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70944. * @param poseData raw pose fromthe device
  70945. */
  70946. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70947. if (poseData) {
  70948. this.rawPose = poseData;
  70949. if (poseData.position) {
  70950. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70951. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70952. this._deviceRoomPosition.z *= -1;
  70953. }
  70954. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70955. this._calculatedPosition.addInPlace(this.position);
  70956. }
  70957. var pose = this.rawPose;
  70958. if (poseData.orientation && pose.orientation) {
  70959. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70960. if (this._mesh) {
  70961. if (this._mesh.getScene().useRightHandedSystem) {
  70962. this._deviceRoomRotationQuaternion.z *= -1;
  70963. this._deviceRoomRotationQuaternion.w *= -1;
  70964. }
  70965. else {
  70966. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70967. }
  70968. }
  70969. // if the camera is set, rotate to the camera's rotation
  70970. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70971. }
  70972. }
  70973. };
  70974. /**
  70975. * Attaches a mesh to the controller
  70976. * @param mesh the mesh to be attached
  70977. */
  70978. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70979. if (this._mesh) {
  70980. this._mesh.parent = null;
  70981. }
  70982. this._mesh = mesh;
  70983. if (this._poseControlledCamera) {
  70984. this._mesh.parent = this._poseControlledCamera;
  70985. }
  70986. if (!this._mesh.rotationQuaternion) {
  70987. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70988. }
  70989. this._meshAttachedObservable.notifyObservers(mesh);
  70990. };
  70991. /**
  70992. * Attaches the controllers mesh to a camera
  70993. * @param camera the camera the mesh should be attached to
  70994. */
  70995. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70996. this._poseControlledCamera = camera;
  70997. if (this._mesh) {
  70998. this._mesh.parent = this._poseControlledCamera;
  70999. }
  71000. };
  71001. /**
  71002. * Disposes of the controller
  71003. */
  71004. PoseEnabledController.prototype.dispose = function () {
  71005. if (this._mesh) {
  71006. this._mesh.dispose();
  71007. }
  71008. this._mesh = null;
  71009. _super.prototype.dispose.call(this);
  71010. };
  71011. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71012. /**
  71013. * The mesh that is attached to the controller
  71014. */
  71015. get: function () {
  71016. return this._mesh;
  71017. },
  71018. enumerable: true,
  71019. configurable: true
  71020. });
  71021. /**
  71022. * Gets the ray of the controller in the direction the controller is pointing
  71023. * @param length the length the resulting ray should be
  71024. * @returns a ray in the direction the controller is pointing
  71025. */
  71026. PoseEnabledController.prototype.getForwardRay = function (length) {
  71027. if (length === void 0) { length = 100; }
  71028. if (!this.mesh) {
  71029. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71030. }
  71031. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71032. var origin = m.getTranslation();
  71033. var forward = new BABYLON.Vector3(0, 0, -1);
  71034. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71035. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71036. return new BABYLON.Ray(origin, direction, length);
  71037. };
  71038. /**
  71039. * Name of the child mesh that can be used to cast a ray from the controller
  71040. */
  71041. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71042. return PoseEnabledController;
  71043. }(BABYLON.Gamepad));
  71044. BABYLON.PoseEnabledController = PoseEnabledController;
  71045. })(BABYLON || (BABYLON = {}));
  71046. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71047. var BABYLON;
  71048. (function (BABYLON) {
  71049. /**
  71050. * Defines the WebVRController object that represents controllers tracked in 3D space
  71051. */
  71052. var WebVRController = /** @class */ (function (_super) {
  71053. __extends(WebVRController, _super);
  71054. /**
  71055. * Creates a new WebVRController from a gamepad
  71056. * @param vrGamepad the gamepad that the WebVRController should be created from
  71057. */
  71058. function WebVRController(vrGamepad) {
  71059. var _this = _super.call(this, vrGamepad) || this;
  71060. // Observables
  71061. /**
  71062. * Fired when the trigger state has changed
  71063. */
  71064. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71065. /**
  71066. * Fired when the main button state has changed
  71067. */
  71068. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71069. /**
  71070. * Fired when the secondary button state has changed
  71071. */
  71072. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71073. /**
  71074. * Fired when the pad state has changed
  71075. */
  71076. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71077. /**
  71078. * Fired when controllers stick values have changed
  71079. */
  71080. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71081. /**
  71082. * X and Y axis corrisponding to the controllers joystick
  71083. */
  71084. _this.pad = { x: 0, y: 0 };
  71085. // avoid GC, store state in a tmp object
  71086. _this._changes = {
  71087. pressChanged: false,
  71088. touchChanged: false,
  71089. valueChanged: false,
  71090. changed: false
  71091. };
  71092. _this._buttons = new Array(vrGamepad.buttons.length);
  71093. _this.hand = vrGamepad.hand;
  71094. return _this;
  71095. }
  71096. /**
  71097. * Fired when a controller button's state has changed
  71098. * @param callback the callback containing the button that was modified
  71099. */
  71100. WebVRController.prototype.onButtonStateChange = function (callback) {
  71101. this._onButtonStateChange = callback;
  71102. };
  71103. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71104. /**
  71105. * The default controller model for the controller
  71106. */
  71107. get: function () {
  71108. return this._defaultModel;
  71109. },
  71110. enumerable: true,
  71111. configurable: true
  71112. });
  71113. /**
  71114. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71115. */
  71116. WebVRController.prototype.update = function () {
  71117. _super.prototype.update.call(this);
  71118. for (var index = 0; index < this._buttons.length; index++) {
  71119. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71120. }
  71121. ;
  71122. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71123. this.pad.x = this.leftStick.x;
  71124. this.pad.y = this.leftStick.y;
  71125. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71126. }
  71127. };
  71128. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71129. if (!newState) {
  71130. newState = {
  71131. pressed: false,
  71132. touched: false,
  71133. value: 0
  71134. };
  71135. }
  71136. if (!currentState) {
  71137. this._buttons[buttonIndex] = {
  71138. pressed: newState.pressed,
  71139. touched: newState.touched,
  71140. value: newState.value
  71141. };
  71142. return;
  71143. }
  71144. this._checkChanges(newState, currentState);
  71145. if (this._changes.changed) {
  71146. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71147. this._handleButtonChange(buttonIndex, newState, this._changes);
  71148. }
  71149. this._buttons[buttonIndex].pressed = newState.pressed;
  71150. this._buttons[buttonIndex].touched = newState.touched;
  71151. // oculus triggers are never 0, thou not touched.
  71152. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71153. };
  71154. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71155. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71156. this._changes.touchChanged = newState.touched !== currentState.touched;
  71157. this._changes.valueChanged = newState.value !== currentState.value;
  71158. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71159. return this._changes;
  71160. };
  71161. /**
  71162. * Disposes of th webVRCOntroller
  71163. */
  71164. WebVRController.prototype.dispose = function () {
  71165. _super.prototype.dispose.call(this);
  71166. this.onTriggerStateChangedObservable.clear();
  71167. this.onMainButtonStateChangedObservable.clear();
  71168. this.onSecondaryButtonStateChangedObservable.clear();
  71169. this.onPadStateChangedObservable.clear();
  71170. this.onPadValuesChangedObservable.clear();
  71171. };
  71172. return WebVRController;
  71173. }(BABYLON.PoseEnabledController));
  71174. BABYLON.WebVRController = WebVRController;
  71175. })(BABYLON || (BABYLON = {}));
  71176. //# sourceMappingURL=babylon.webVRController.js.map
  71177. var BABYLON;
  71178. (function (BABYLON) {
  71179. /**
  71180. * Oculus Touch Controller
  71181. */
  71182. var OculusTouchController = /** @class */ (function (_super) {
  71183. __extends(OculusTouchController, _super);
  71184. /**
  71185. * Creates a new OculusTouchController from a gamepad
  71186. * @param vrGamepad the gamepad that the controller should be created from
  71187. */
  71188. function OculusTouchController(vrGamepad) {
  71189. var _this = _super.call(this, vrGamepad) || this;
  71190. /**
  71191. * Fired when the secondary trigger on this controller is modified
  71192. */
  71193. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71194. /**
  71195. * Fired when the thumb rest on this controller is modified
  71196. */
  71197. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71198. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71199. return _this;
  71200. }
  71201. /**
  71202. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71203. * @param scene scene in which to add meshes
  71204. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71205. */
  71206. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71207. var _this = this;
  71208. var meshName;
  71209. // Hand
  71210. if (this.hand === 'left') {
  71211. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71212. }
  71213. else { // Right is the default if no hand is specified
  71214. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71215. }
  71216. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71217. /*
  71218. Parent Mesh name: oculus_touch_left
  71219. - body
  71220. - trigger
  71221. - thumbstick
  71222. - grip
  71223. - button_y
  71224. - button_x
  71225. - button_enter
  71226. */
  71227. _this._defaultModel = newMeshes[1];
  71228. _this.attachToMesh(_this._defaultModel);
  71229. if (meshLoaded) {
  71230. meshLoaded(_this._defaultModel);
  71231. }
  71232. });
  71233. };
  71234. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71235. /**
  71236. * Fired when the A button on this controller is modified
  71237. */
  71238. get: function () {
  71239. if (this.hand === 'right') {
  71240. return this.onMainButtonStateChangedObservable;
  71241. }
  71242. else {
  71243. throw new Error('No A button on left hand');
  71244. }
  71245. },
  71246. enumerable: true,
  71247. configurable: true
  71248. });
  71249. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71250. /**
  71251. * Fired when the B button on this controller is modified
  71252. */
  71253. get: function () {
  71254. if (this.hand === 'right') {
  71255. return this.onSecondaryButtonStateChangedObservable;
  71256. }
  71257. else {
  71258. throw new Error('No B button on left hand');
  71259. }
  71260. },
  71261. enumerable: true,
  71262. configurable: true
  71263. });
  71264. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71265. /**
  71266. * Fired when the X button on this controller is modified
  71267. */
  71268. get: function () {
  71269. if (this.hand === 'left') {
  71270. return this.onMainButtonStateChangedObservable;
  71271. }
  71272. else {
  71273. throw new Error('No X button on right hand');
  71274. }
  71275. },
  71276. enumerable: true,
  71277. configurable: true
  71278. });
  71279. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71280. /**
  71281. * Fired when the Y button on this controller is modified
  71282. */
  71283. get: function () {
  71284. if (this.hand === 'left') {
  71285. return this.onSecondaryButtonStateChangedObservable;
  71286. }
  71287. else {
  71288. throw new Error('No Y button on right hand');
  71289. }
  71290. },
  71291. enumerable: true,
  71292. configurable: true
  71293. });
  71294. /**
  71295. * Called once for each button that changed state since the last frame
  71296. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71297. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71298. * 2) secondary trigger (same)
  71299. * 3) A (right) X (left), touch, pressed = value
  71300. * 4) B / Y
  71301. * 5) thumb rest
  71302. * @param buttonIdx Which button index changed
  71303. * @param state New state of the button
  71304. * @param changes Which properties on the state changed since last frame
  71305. */
  71306. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71307. var notifyObject = state; //{ state: state, changes: changes };
  71308. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71309. switch (buttonIdx) {
  71310. case 0:
  71311. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71312. return;
  71313. case 1: // index trigger
  71314. if (this._defaultModel) {
  71315. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71316. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71317. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71318. }
  71319. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71320. return;
  71321. case 2: // secondary trigger
  71322. if (this._defaultModel) {
  71323. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71324. }
  71325. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71326. return;
  71327. case 3:
  71328. if (this._defaultModel) {
  71329. if (notifyObject.pressed) {
  71330. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71331. }
  71332. else {
  71333. (this._defaultModel.getChildren()[1]).position.y = 0;
  71334. }
  71335. }
  71336. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71337. return;
  71338. case 4:
  71339. if (this._defaultModel) {
  71340. if (notifyObject.pressed) {
  71341. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71342. }
  71343. else {
  71344. (this._defaultModel.getChildren()[2]).position.y = 0;
  71345. }
  71346. }
  71347. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71348. return;
  71349. case 5:
  71350. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71351. return;
  71352. }
  71353. };
  71354. /**
  71355. * Base Url for the controller model.
  71356. */
  71357. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71358. /**
  71359. * File name for the left controller model.
  71360. */
  71361. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71362. /**
  71363. * File name for the right controller model.
  71364. */
  71365. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71366. return OculusTouchController;
  71367. }(BABYLON.WebVRController));
  71368. BABYLON.OculusTouchController = OculusTouchController;
  71369. })(BABYLON || (BABYLON = {}));
  71370. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71371. var BABYLON;
  71372. (function (BABYLON) {
  71373. /**
  71374. * Vive Controller
  71375. */
  71376. var ViveController = /** @class */ (function (_super) {
  71377. __extends(ViveController, _super);
  71378. /**
  71379. * Creates a new ViveController from a gamepad
  71380. * @param vrGamepad the gamepad that the controller should be created from
  71381. */
  71382. function ViveController(vrGamepad) {
  71383. var _this = _super.call(this, vrGamepad) || this;
  71384. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71385. _this._invertLeftStickY = true;
  71386. return _this;
  71387. }
  71388. /**
  71389. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71390. * @param scene scene in which to add meshes
  71391. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71392. */
  71393. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71394. var _this = this;
  71395. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71396. /*
  71397. Parent Mesh name: ViveWand
  71398. - body
  71399. - r_gripper
  71400. - l_gripper
  71401. - menu_button
  71402. - system_button
  71403. - trackpad
  71404. - trigger
  71405. - LED
  71406. */
  71407. _this._defaultModel = newMeshes[1];
  71408. _this.attachToMesh(_this._defaultModel);
  71409. if (meshLoaded) {
  71410. meshLoaded(_this._defaultModel);
  71411. }
  71412. });
  71413. };
  71414. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71415. /**
  71416. * Fired when the left button on this controller is modified
  71417. */
  71418. get: function () {
  71419. return this.onMainButtonStateChangedObservable;
  71420. },
  71421. enumerable: true,
  71422. configurable: true
  71423. });
  71424. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71425. /**
  71426. * Fired when the right button on this controller is modified
  71427. */
  71428. get: function () {
  71429. return this.onMainButtonStateChangedObservable;
  71430. },
  71431. enumerable: true,
  71432. configurable: true
  71433. });
  71434. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71435. /**
  71436. * Fired when the menu button on this controller is modified
  71437. */
  71438. get: function () {
  71439. return this.onSecondaryButtonStateChangedObservable;
  71440. },
  71441. enumerable: true,
  71442. configurable: true
  71443. });
  71444. /**
  71445. * Called once for each button that changed state since the last frame
  71446. * Vive mapping:
  71447. * 0: touchpad
  71448. * 1: trigger
  71449. * 2: left AND right buttons
  71450. * 3: menu button
  71451. * @param buttonIdx Which button index changed
  71452. * @param state New state of the button
  71453. * @param changes Which properties on the state changed since last frame
  71454. */
  71455. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71456. var notifyObject = state; //{ state: state, changes: changes };
  71457. switch (buttonIdx) {
  71458. case 0:
  71459. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71460. return;
  71461. case 1: // index trigger
  71462. if (this._defaultModel) {
  71463. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71464. }
  71465. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71466. return;
  71467. case 2: // left AND right button
  71468. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71469. return;
  71470. case 3:
  71471. if (this._defaultModel) {
  71472. if (notifyObject.pressed) {
  71473. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71474. }
  71475. else {
  71476. (this._defaultModel.getChildren()[2]).position.y = 0;
  71477. }
  71478. }
  71479. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71480. return;
  71481. }
  71482. };
  71483. /**
  71484. * Base Url for the controller model.
  71485. */
  71486. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71487. /**
  71488. * File name for the controller model.
  71489. */
  71490. ViveController.MODEL_FILENAME = 'wand.babylon';
  71491. return ViveController;
  71492. }(BABYLON.WebVRController));
  71493. BABYLON.ViveController = ViveController;
  71494. })(BABYLON || (BABYLON = {}));
  71495. //# sourceMappingURL=babylon.viveController.js.map
  71496. var BABYLON;
  71497. (function (BABYLON) {
  71498. /**
  71499. * Generic Controller
  71500. */
  71501. var GenericController = /** @class */ (function (_super) {
  71502. __extends(GenericController, _super);
  71503. /**
  71504. * Creates a new GenericController from a gamepad
  71505. * @param vrGamepad the gamepad that the controller should be created from
  71506. */
  71507. function GenericController(vrGamepad) {
  71508. return _super.call(this, vrGamepad) || this;
  71509. }
  71510. /**
  71511. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71512. * @param scene scene in which to add meshes
  71513. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71514. */
  71515. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71516. var _this = this;
  71517. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71518. _this._defaultModel = newMeshes[1];
  71519. _this.attachToMesh(_this._defaultModel);
  71520. if (meshLoaded) {
  71521. meshLoaded(_this._defaultModel);
  71522. }
  71523. });
  71524. };
  71525. /**
  71526. * Called once for each button that changed state since the last frame
  71527. * @param buttonIdx Which button index changed
  71528. * @param state New state of the button
  71529. * @param changes Which properties on the state changed since last frame
  71530. */
  71531. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71532. console.log("Button id: " + buttonIdx + "state: ");
  71533. console.dir(state);
  71534. };
  71535. /**
  71536. * Base Url for the controller model.
  71537. */
  71538. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71539. /**
  71540. * File name for the controller model.
  71541. */
  71542. GenericController.MODEL_FILENAME = 'generic.babylon';
  71543. return GenericController;
  71544. }(BABYLON.WebVRController));
  71545. BABYLON.GenericController = GenericController;
  71546. })(BABYLON || (BABYLON = {}));
  71547. //# sourceMappingURL=babylon.genericController.js.map
  71548. var BABYLON;
  71549. (function (BABYLON) {
  71550. /**
  71551. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71552. */
  71553. var LoadedMeshInfo = /** @class */ (function () {
  71554. function LoadedMeshInfo() {
  71555. /**
  71556. * Map of the button meshes contained in the controller
  71557. */
  71558. this.buttonMeshes = {};
  71559. /**
  71560. * Map of the axis meshes contained in the controller
  71561. */
  71562. this.axisMeshes = {};
  71563. }
  71564. return LoadedMeshInfo;
  71565. }());
  71566. /**
  71567. * Defines the WindowsMotionController object that the state of the windows motion controller
  71568. */
  71569. var WindowsMotionController = /** @class */ (function (_super) {
  71570. __extends(WindowsMotionController, _super);
  71571. /**
  71572. * Creates a new WindowsMotionController from a gamepad
  71573. * @param vrGamepad the gamepad that the controller should be created from
  71574. */
  71575. function WindowsMotionController(vrGamepad) {
  71576. var _this = _super.call(this, vrGamepad) || this;
  71577. _this._mapping = {
  71578. // Semantic button names
  71579. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71580. // A mapping of the button name to glTF model node name
  71581. // that should be transformed by button value.
  71582. buttonMeshNames: {
  71583. 'trigger': 'SELECT',
  71584. 'menu': 'MENU',
  71585. 'grip': 'GRASP',
  71586. 'thumbstick': 'THUMBSTICK_PRESS',
  71587. 'trackpad': 'TOUCHPAD_PRESS'
  71588. },
  71589. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71590. buttonObservableNames: {
  71591. 'trigger': 'onTriggerStateChangedObservable',
  71592. 'menu': 'onSecondaryButtonStateChangedObservable',
  71593. 'grip': 'onMainButtonStateChangedObservable',
  71594. 'thumbstick': 'onPadStateChangedObservable',
  71595. 'trackpad': 'onTrackpadChangedObservable'
  71596. },
  71597. // A mapping of the axis name to glTF model node name
  71598. // that should be transformed by axis value.
  71599. // This array mirrors the browserGamepad.axes array, such that
  71600. // the mesh corresponding to axis 0 is in this array index 0.
  71601. axisMeshNames: [
  71602. 'THUMBSTICK_X',
  71603. 'THUMBSTICK_Y',
  71604. 'TOUCHPAD_TOUCH_X',
  71605. 'TOUCHPAD_TOUCH_Y'
  71606. ],
  71607. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71608. };
  71609. /**
  71610. * Fired when the trackpad on this controller is clicked
  71611. */
  71612. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71613. /**
  71614. * Fired when the trackpad on this controller is modified
  71615. */
  71616. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71617. /**
  71618. * The current x and y values of this controller's trackpad
  71619. */
  71620. _this.trackpad = { x: 0, y: 0 };
  71621. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71622. _this._loadedMeshInfo = null;
  71623. return _this;
  71624. }
  71625. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71626. /**
  71627. * Fired when the trigger on this controller is modified
  71628. */
  71629. get: function () {
  71630. return this.onTriggerStateChangedObservable;
  71631. },
  71632. enumerable: true,
  71633. configurable: true
  71634. });
  71635. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71636. /**
  71637. * Fired when the menu button on this controller is modified
  71638. */
  71639. get: function () {
  71640. return this.onSecondaryButtonStateChangedObservable;
  71641. },
  71642. enumerable: true,
  71643. configurable: true
  71644. });
  71645. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71646. /**
  71647. * Fired when the grip button on this controller is modified
  71648. */
  71649. get: function () {
  71650. return this.onMainButtonStateChangedObservable;
  71651. },
  71652. enumerable: true,
  71653. configurable: true
  71654. });
  71655. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71656. /**
  71657. * Fired when the thumbstick button on this controller is modified
  71658. */
  71659. get: function () {
  71660. return this.onPadStateChangedObservable;
  71661. },
  71662. enumerable: true,
  71663. configurable: true
  71664. });
  71665. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71666. /**
  71667. * Fired when the touchpad button on this controller is modified
  71668. */
  71669. get: function () {
  71670. return this.onTrackpadChangedObservable;
  71671. },
  71672. enumerable: true,
  71673. configurable: true
  71674. });
  71675. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71676. /**
  71677. * Fired when the touchpad values on this controller are modified
  71678. */
  71679. get: function () {
  71680. return this.onTrackpadValuesChangedObservable;
  71681. },
  71682. enumerable: true,
  71683. configurable: true
  71684. });
  71685. /**
  71686. * Called once per frame by the engine.
  71687. */
  71688. WindowsMotionController.prototype.update = function () {
  71689. _super.prototype.update.call(this);
  71690. if (this.browserGamepad.axes) {
  71691. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71692. this.trackpad.x = this.browserGamepad["axes"][2];
  71693. this.trackpad.y = this.browserGamepad["axes"][3];
  71694. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71695. }
  71696. // Only need to animate axes if there is a loaded mesh
  71697. if (this._loadedMeshInfo) {
  71698. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71699. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71700. }
  71701. }
  71702. }
  71703. };
  71704. /**
  71705. * Called once for each button that changed state since the last frame
  71706. * @param buttonIdx Which button index changed
  71707. * @param state New state of the button
  71708. * @param changes Which properties on the state changed since last frame
  71709. */
  71710. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71711. var buttonName = this._mapping.buttons[buttonIdx];
  71712. if (!buttonName) {
  71713. return;
  71714. }
  71715. // Only emit events for buttons that we know how to map from index to name
  71716. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71717. if (observable) {
  71718. observable.notifyObservers(state);
  71719. }
  71720. this._lerpButtonTransform(buttonName, state.value);
  71721. };
  71722. /**
  71723. * Moves the buttons on the controller mesh based on their current state
  71724. * @param buttonName the name of the button to move
  71725. * @param buttonValue the value of the button which determines the buttons new position
  71726. */
  71727. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71728. // If there is no loaded mesh, there is nothing to transform.
  71729. if (!this._loadedMeshInfo) {
  71730. return;
  71731. }
  71732. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71733. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71734. return;
  71735. }
  71736. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71737. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71738. };
  71739. /**
  71740. * Moves the axis on the controller mesh based on its current state
  71741. * @param axis the index of the axis
  71742. * @param axisValue the value of the axis which determines the meshes new position
  71743. * @hidden
  71744. */
  71745. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71746. if (!this._loadedMeshInfo) {
  71747. return;
  71748. }
  71749. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71750. if (!meshInfo) {
  71751. return;
  71752. }
  71753. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71754. return;
  71755. }
  71756. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71757. var lerpValue = axisValue * 0.5 + 0.5;
  71758. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71759. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71760. };
  71761. /**
  71762. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71763. * @param scene scene in which to add meshes
  71764. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71765. */
  71766. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71767. var _this = this;
  71768. if (forceDefault === void 0) { forceDefault = false; }
  71769. var path;
  71770. var filename;
  71771. // Checking if GLB loader is present
  71772. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71773. // Determine the device specific folder based on the ID suffix
  71774. var device = 'default';
  71775. if (this.id && !forceDefault) {
  71776. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71777. device = ((match && match[0]) || device);
  71778. }
  71779. // Hand
  71780. if (this.hand === 'left') {
  71781. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71782. }
  71783. else { // Right is the default if no hand is specified
  71784. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71785. }
  71786. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71787. }
  71788. else {
  71789. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71790. path = BABYLON.GenericController.MODEL_BASE_URL;
  71791. filename = BABYLON.GenericController.MODEL_FILENAME;
  71792. }
  71793. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71794. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71795. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71796. if (!_this._loadedMeshInfo) {
  71797. return;
  71798. }
  71799. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71800. _this.attachToMesh(_this._defaultModel);
  71801. if (meshLoaded) {
  71802. meshLoaded(_this._defaultModel);
  71803. }
  71804. }, null, function (scene, message) {
  71805. BABYLON.Tools.Log(message);
  71806. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71807. if (!forceDefault) {
  71808. _this.initControllerMesh(scene, meshLoaded, true);
  71809. }
  71810. });
  71811. };
  71812. /**
  71813. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71814. * can be transformed by button presses and axes values, based on this._mapping.
  71815. *
  71816. * @param scene scene in which the meshes exist
  71817. * @param meshes list of meshes that make up the controller model to process
  71818. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71819. */
  71820. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71821. var loadedMeshInfo = null;
  71822. // Create a new mesh to contain the glTF hierarchy
  71823. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71824. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71825. var childMesh = null;
  71826. for (var i = 0; i < meshes.length; i++) {
  71827. var mesh = meshes[i];
  71828. if (!mesh.parent) {
  71829. // Exclude controller meshes from picking results
  71830. mesh.isPickable = false;
  71831. // Handle root node, attach to the new parentMesh
  71832. childMesh = mesh;
  71833. break;
  71834. }
  71835. }
  71836. if (childMesh) {
  71837. childMesh.setParent(parentMesh);
  71838. // Create our mesh info. Note that this method will always return non-null.
  71839. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71840. }
  71841. else {
  71842. BABYLON.Tools.Warn('Could not find root node in model file.');
  71843. }
  71844. return loadedMeshInfo;
  71845. };
  71846. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71847. var loadedMeshInfo = new LoadedMeshInfo();
  71848. var i;
  71849. loadedMeshInfo.rootNode = rootNode;
  71850. // Reset the caches
  71851. loadedMeshInfo.buttonMeshes = {};
  71852. loadedMeshInfo.axisMeshes = {};
  71853. // Button Meshes
  71854. for (i = 0; i < this._mapping.buttons.length; i++) {
  71855. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71856. if (!buttonMeshName) {
  71857. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71858. continue;
  71859. }
  71860. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71861. if (!buttonMesh) {
  71862. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71863. continue;
  71864. }
  71865. var buttonMeshInfo = {
  71866. index: i,
  71867. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71868. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71869. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71870. };
  71871. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71872. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71873. }
  71874. else {
  71875. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71876. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71877. '(VALUE: ' + !!buttonMeshInfo.value +
  71878. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71879. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71880. ')');
  71881. }
  71882. }
  71883. // Axis Meshes
  71884. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71885. var axisMeshName = this._mapping.axisMeshNames[i];
  71886. if (!axisMeshName) {
  71887. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71888. continue;
  71889. }
  71890. var axisMesh = getChildByName(rootNode, axisMeshName);
  71891. if (!axisMesh) {
  71892. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71893. continue;
  71894. }
  71895. var axisMeshInfo = {
  71896. index: i,
  71897. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71898. min: getImmediateChildByName(axisMesh, 'MIN'),
  71899. max: getImmediateChildByName(axisMesh, 'MAX')
  71900. };
  71901. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71902. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71903. }
  71904. else {
  71905. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71906. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71907. '(VALUE: ' + !!axisMeshInfo.value +
  71908. ', MIN: ' + !!axisMeshInfo.min +
  71909. ', MAX:' + !!axisMeshInfo.max +
  71910. ')');
  71911. }
  71912. }
  71913. // Pointing Ray
  71914. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71915. if (!loadedMeshInfo.pointingPoseNode) {
  71916. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71917. }
  71918. return loadedMeshInfo;
  71919. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71920. function getChildByName(node, name) {
  71921. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71922. }
  71923. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71924. function getImmediateChildByName(node, name) {
  71925. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71926. }
  71927. };
  71928. /**
  71929. * Gets the ray of the controller in the direction the controller is pointing
  71930. * @param length the length the resulting ray should be
  71931. * @returns a ray in the direction the controller is pointing
  71932. */
  71933. WindowsMotionController.prototype.getForwardRay = function (length) {
  71934. if (length === void 0) { length = 100; }
  71935. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71936. return _super.prototype.getForwardRay.call(this, length);
  71937. }
  71938. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71939. var origin = m.getTranslation();
  71940. var forward = new BABYLON.Vector3(0, 0, -1);
  71941. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71942. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71943. return new BABYLON.Ray(origin, direction, length);
  71944. };
  71945. /**
  71946. * Disposes of the controller
  71947. */
  71948. WindowsMotionController.prototype.dispose = function () {
  71949. _super.prototype.dispose.call(this);
  71950. this.onTrackpadChangedObservable.clear();
  71951. };
  71952. /**
  71953. * The base url used to load the left and right controller models
  71954. */
  71955. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71956. /**
  71957. * The name of the left controller model file
  71958. */
  71959. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71960. /**
  71961. * The name of the right controller model file
  71962. */
  71963. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71964. /**
  71965. * The controller name prefix for this controller type
  71966. */
  71967. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71968. /**
  71969. * The controller id pattern for this controller type
  71970. */
  71971. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71972. return WindowsMotionController;
  71973. }(BABYLON.WebVRController));
  71974. BABYLON.WindowsMotionController = WindowsMotionController;
  71975. })(BABYLON || (BABYLON = {}));
  71976. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71977. var BABYLON;
  71978. (function (BABYLON) {
  71979. /**
  71980. * Gear VR Controller
  71981. */
  71982. var GearVRController = /** @class */ (function (_super) {
  71983. __extends(GearVRController, _super);
  71984. /**
  71985. * Creates a new GearVRController from a gamepad
  71986. * @param vrGamepad the gamepad that the controller should be created from
  71987. */
  71988. function GearVRController(vrGamepad) {
  71989. var _this = _super.call(this, vrGamepad) || this;
  71990. _this._buttonIndexToObservableNameMap = [
  71991. 'onTrackpadChangedObservable',
  71992. 'onTriggerStateChangedObservable' // Trigger
  71993. ];
  71994. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71995. return _this;
  71996. }
  71997. /**
  71998. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71999. * @param scene scene in which to add meshes
  72000. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72001. */
  72002. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72003. var _this = this;
  72004. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72005. _this._defaultModel = newMeshes[1];
  72006. _this.attachToMesh(_this._defaultModel);
  72007. if (meshLoaded) {
  72008. meshLoaded(_this._defaultModel);
  72009. }
  72010. });
  72011. };
  72012. /**
  72013. * Called once for each button that changed state since the last frame
  72014. * @param buttonIdx Which button index changed
  72015. * @param state New state of the button
  72016. * @param changes Which properties on the state changed since last frame
  72017. */
  72018. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72019. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72020. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72021. // Only emit events for buttons that we know how to map from index to observable
  72022. var observable = this[observableName];
  72023. if (observable) {
  72024. observable.notifyObservers(state);
  72025. }
  72026. }
  72027. };
  72028. /**
  72029. * Base Url for the controller model.
  72030. */
  72031. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72032. /**
  72033. * File name for the controller model.
  72034. */
  72035. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72036. /**
  72037. * Gamepad Id prefix used to identify this controller.
  72038. */
  72039. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72040. return GearVRController;
  72041. }(BABYLON.WebVRController));
  72042. BABYLON.GearVRController = GearVRController;
  72043. })(BABYLON || (BABYLON = {}));
  72044. //# sourceMappingURL=babylon.gearVRController.js.map
  72045. var BABYLON;
  72046. (function (BABYLON) {
  72047. /**
  72048. * Google Daydream controller
  72049. */
  72050. var DaydreamController = /** @class */ (function (_super) {
  72051. __extends(DaydreamController, _super);
  72052. /**
  72053. * Creates a new DaydreamController from a gamepad
  72054. * @param vrGamepad the gamepad that the controller should be created from
  72055. */
  72056. function DaydreamController(vrGamepad) {
  72057. var _this = _super.call(this, vrGamepad) || this;
  72058. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72059. return _this;
  72060. }
  72061. /**
  72062. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72063. * @param scene scene in which to add meshes
  72064. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72065. */
  72066. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72067. var _this = this;
  72068. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72069. _this._defaultModel = newMeshes[1];
  72070. _this.attachToMesh(_this._defaultModel);
  72071. if (meshLoaded) {
  72072. meshLoaded(_this._defaultModel);
  72073. }
  72074. });
  72075. };
  72076. /**
  72077. * Called once for each button that changed state since the last frame
  72078. * @param buttonIdx Which button index changed
  72079. * @param state New state of the button
  72080. * @param changes Which properties on the state changed since last frame
  72081. */
  72082. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72083. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72084. if (buttonIdx === 0) {
  72085. var observable = this.onTriggerStateChangedObservable;
  72086. if (observable) {
  72087. observable.notifyObservers(state);
  72088. }
  72089. }
  72090. else {
  72091. // If the app or home buttons are ever made available
  72092. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72093. }
  72094. };
  72095. /**
  72096. * Base Url for the controller model.
  72097. */
  72098. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72099. /**
  72100. * File name for the controller model.
  72101. */
  72102. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72103. /**
  72104. * Gamepad Id prefix used to identify Daydream Controller.
  72105. */
  72106. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72107. return DaydreamController;
  72108. }(BABYLON.WebVRController));
  72109. BABYLON.DaydreamController = DaydreamController;
  72110. })(BABYLON || (BABYLON = {}));
  72111. //# sourceMappingURL=babylon.daydreamController.js.map
  72112. var BABYLON;
  72113. (function (BABYLON) {
  72114. var FollowCamera = /** @class */ (function (_super) {
  72115. __extends(FollowCamera, _super);
  72116. function FollowCamera(name, position, scene, lockedTarget) {
  72117. if (lockedTarget === void 0) { lockedTarget = null; }
  72118. var _this = _super.call(this, name, position, scene) || this;
  72119. _this.radius = 12;
  72120. _this.rotationOffset = 0;
  72121. _this.heightOffset = 4;
  72122. _this.cameraAcceleration = 0.05;
  72123. _this.maxCameraSpeed = 20;
  72124. _this.lockedTarget = lockedTarget;
  72125. return _this;
  72126. }
  72127. FollowCamera.prototype.getRadians = function (degrees) {
  72128. return degrees * Math.PI / 180;
  72129. };
  72130. FollowCamera.prototype.follow = function (cameraTarget) {
  72131. if (!cameraTarget)
  72132. return;
  72133. var yRotation;
  72134. if (cameraTarget.rotationQuaternion) {
  72135. var rotMatrix = new BABYLON.Matrix();
  72136. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72137. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72138. }
  72139. else {
  72140. yRotation = cameraTarget.rotation.y;
  72141. }
  72142. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72143. var targetPosition = cameraTarget.getAbsolutePosition();
  72144. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72145. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72146. var dx = targetX - this.position.x;
  72147. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72148. var dz = (targetZ) - this.position.z;
  72149. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72150. var vy = dy * this.cameraAcceleration;
  72151. var vz = dz * this.cameraAcceleration * 2;
  72152. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72153. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72154. }
  72155. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72156. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72157. }
  72158. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72159. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72160. }
  72161. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72162. this.setTarget(targetPosition);
  72163. };
  72164. FollowCamera.prototype._checkInputs = function () {
  72165. _super.prototype._checkInputs.call(this);
  72166. if (this.lockedTarget) {
  72167. this.follow(this.lockedTarget);
  72168. }
  72169. };
  72170. FollowCamera.prototype.getClassName = function () {
  72171. return "FollowCamera";
  72172. };
  72173. __decorate([
  72174. BABYLON.serialize()
  72175. ], FollowCamera.prototype, "radius", void 0);
  72176. __decorate([
  72177. BABYLON.serialize()
  72178. ], FollowCamera.prototype, "rotationOffset", void 0);
  72179. __decorate([
  72180. BABYLON.serialize()
  72181. ], FollowCamera.prototype, "heightOffset", void 0);
  72182. __decorate([
  72183. BABYLON.serialize()
  72184. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72185. __decorate([
  72186. BABYLON.serialize()
  72187. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72188. __decorate([
  72189. BABYLON.serializeAsMeshReference("lockedTargetId")
  72190. ], FollowCamera.prototype, "lockedTarget", void 0);
  72191. return FollowCamera;
  72192. }(BABYLON.TargetCamera));
  72193. BABYLON.FollowCamera = FollowCamera;
  72194. var ArcFollowCamera = /** @class */ (function (_super) {
  72195. __extends(ArcFollowCamera, _super);
  72196. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72197. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72198. _this.alpha = alpha;
  72199. _this.beta = beta;
  72200. _this.radius = radius;
  72201. _this.target = target;
  72202. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72203. _this.follow();
  72204. return _this;
  72205. }
  72206. ArcFollowCamera.prototype.follow = function () {
  72207. if (!this.target) {
  72208. return;
  72209. }
  72210. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72211. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72212. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72213. var targetPosition = this.target.getAbsolutePosition();
  72214. this.position = targetPosition.add(this._cartesianCoordinates);
  72215. this.setTarget(targetPosition);
  72216. };
  72217. ArcFollowCamera.prototype._checkInputs = function () {
  72218. _super.prototype._checkInputs.call(this);
  72219. this.follow();
  72220. };
  72221. ArcFollowCamera.prototype.getClassName = function () {
  72222. return "ArcFollowCamera";
  72223. };
  72224. return ArcFollowCamera;
  72225. }(BABYLON.TargetCamera));
  72226. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72227. })(BABYLON || (BABYLON = {}));
  72228. //# sourceMappingURL=babylon.followCamera.js.map
  72229. var BABYLON;
  72230. (function (BABYLON) {
  72231. // We're mainly based on the logic defined into the FreeCamera code
  72232. var UniversalCamera = /** @class */ (function (_super) {
  72233. __extends(UniversalCamera, _super);
  72234. //-- end properties for backward compatibility for inputs
  72235. function UniversalCamera(name, position, scene) {
  72236. var _this = _super.call(this, name, position, scene) || this;
  72237. _this.inputs.addGamepad();
  72238. return _this;
  72239. }
  72240. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72241. //-- Begin properties for backward compatibility for inputs
  72242. get: function () {
  72243. var gamepad = this.inputs.attached["gamepad"];
  72244. if (gamepad)
  72245. return gamepad.gamepadAngularSensibility;
  72246. return 0;
  72247. },
  72248. set: function (value) {
  72249. var gamepad = this.inputs.attached["gamepad"];
  72250. if (gamepad)
  72251. gamepad.gamepadAngularSensibility = value;
  72252. },
  72253. enumerable: true,
  72254. configurable: true
  72255. });
  72256. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72257. get: function () {
  72258. var gamepad = this.inputs.attached["gamepad"];
  72259. if (gamepad)
  72260. return gamepad.gamepadMoveSensibility;
  72261. return 0;
  72262. },
  72263. set: function (value) {
  72264. var gamepad = this.inputs.attached["gamepad"];
  72265. if (gamepad)
  72266. gamepad.gamepadMoveSensibility = value;
  72267. },
  72268. enumerable: true,
  72269. configurable: true
  72270. });
  72271. UniversalCamera.prototype.getClassName = function () {
  72272. return "UniversalCamera";
  72273. };
  72274. return UniversalCamera;
  72275. }(BABYLON.TouchCamera));
  72276. BABYLON.UniversalCamera = UniversalCamera;
  72277. })(BABYLON || (BABYLON = {}));
  72278. //# sourceMappingURL=babylon.universalCamera.js.map
  72279. var BABYLON;
  72280. (function (BABYLON) {
  72281. // We're mainly based on the logic defined into the FreeCamera code
  72282. var GamepadCamera = /** @class */ (function (_super) {
  72283. __extends(GamepadCamera, _super);
  72284. //-- end properties for backward compatibility for inputs
  72285. function GamepadCamera(name, position, scene) {
  72286. return _super.call(this, name, position, scene) || this;
  72287. }
  72288. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72289. //-- Begin properties for backward compatibility for inputs
  72290. get: function () {
  72291. var gamepad = this.inputs.attached["gamepad"];
  72292. if (gamepad)
  72293. return gamepad.gamepadAngularSensibility;
  72294. return 0;
  72295. },
  72296. set: function (value) {
  72297. var gamepad = this.inputs.attached["gamepad"];
  72298. if (gamepad)
  72299. gamepad.gamepadAngularSensibility = value;
  72300. },
  72301. enumerable: true,
  72302. configurable: true
  72303. });
  72304. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72305. get: function () {
  72306. var gamepad = this.inputs.attached["gamepad"];
  72307. if (gamepad)
  72308. return gamepad.gamepadMoveSensibility;
  72309. return 0;
  72310. },
  72311. set: function (value) {
  72312. var gamepad = this.inputs.attached["gamepad"];
  72313. if (gamepad)
  72314. gamepad.gamepadMoveSensibility = value;
  72315. },
  72316. enumerable: true,
  72317. configurable: true
  72318. });
  72319. GamepadCamera.prototype.getClassName = function () {
  72320. return "GamepadCamera";
  72321. };
  72322. return GamepadCamera;
  72323. }(BABYLON.UniversalCamera));
  72324. BABYLON.GamepadCamera = GamepadCamera;
  72325. })(BABYLON || (BABYLON = {}));
  72326. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72327. var BABYLON;
  72328. (function (BABYLON) {
  72329. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72330. function PostProcessRenderPipelineManager() {
  72331. this._renderPipelines = {};
  72332. }
  72333. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72334. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72335. };
  72336. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72337. if (unique === void 0) { unique = false; }
  72338. var renderPipeline = this._renderPipelines[renderPipelineName];
  72339. if (!renderPipeline) {
  72340. return;
  72341. }
  72342. renderPipeline._attachCameras(cameras, unique);
  72343. };
  72344. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72345. var renderPipeline = this._renderPipelines[renderPipelineName];
  72346. if (!renderPipeline) {
  72347. return;
  72348. }
  72349. renderPipeline._detachCameras(cameras);
  72350. };
  72351. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72352. var renderPipeline = this._renderPipelines[renderPipelineName];
  72353. if (!renderPipeline) {
  72354. return;
  72355. }
  72356. renderPipeline._enableEffect(renderEffectName, cameras);
  72357. };
  72358. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72359. var renderPipeline = this._renderPipelines[renderPipelineName];
  72360. if (!renderPipeline) {
  72361. return;
  72362. }
  72363. renderPipeline._disableEffect(renderEffectName, cameras);
  72364. };
  72365. PostProcessRenderPipelineManager.prototype.update = function () {
  72366. for (var renderPipelineName in this._renderPipelines) {
  72367. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72368. var pipeline = this._renderPipelines[renderPipelineName];
  72369. if (!pipeline.isSupported) {
  72370. pipeline.dispose();
  72371. delete this._renderPipelines[renderPipelineName];
  72372. }
  72373. else {
  72374. pipeline._update();
  72375. }
  72376. }
  72377. }
  72378. };
  72379. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72380. for (var renderPipelineName in this._renderPipelines) {
  72381. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72382. var pipeline = this._renderPipelines[renderPipelineName];
  72383. pipeline._rebuild();
  72384. }
  72385. }
  72386. };
  72387. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72388. for (var renderPipelineName in this._renderPipelines) {
  72389. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72390. var pipeline = this._renderPipelines[renderPipelineName];
  72391. pipeline.dispose();
  72392. }
  72393. }
  72394. };
  72395. return PostProcessRenderPipelineManager;
  72396. }());
  72397. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72398. })(BABYLON || (BABYLON = {}));
  72399. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72400. var BABYLON;
  72401. (function (BABYLON) {
  72402. /**
  72403. * This represents a set of one or more post processes in Babylon.
  72404. * A post process can be used to apply a shader to a texture after it is rendered.
  72405. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72406. */
  72407. var PostProcessRenderEffect = /** @class */ (function () {
  72408. /**
  72409. * Instantiates a post process render effect.
  72410. * A post process can be used to apply a shader to a texture after it is rendered.
  72411. * @param engine The engine the effect is tied to
  72412. * @param name The name of the effect
  72413. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72414. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72415. */
  72416. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72417. this._name = name;
  72418. this._singleInstance = singleInstance || true;
  72419. this._getPostProcesses = getPostProcesses;
  72420. this._cameras = {};
  72421. this._indicesForCamera = {};
  72422. this._postProcesses = {};
  72423. }
  72424. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72425. /**
  72426. * Checks if all the post processes in the effect are supported.
  72427. */
  72428. get: function () {
  72429. for (var index in this._postProcesses) {
  72430. if (this._postProcesses.hasOwnProperty(index)) {
  72431. var pps = this._postProcesses[index];
  72432. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72433. if (!pps[ppIndex].isSupported) {
  72434. return false;
  72435. }
  72436. }
  72437. }
  72438. }
  72439. return true;
  72440. },
  72441. enumerable: true,
  72442. configurable: true
  72443. });
  72444. /**
  72445. * Updates the current state of the effect
  72446. */
  72447. PostProcessRenderEffect.prototype._update = function () {
  72448. };
  72449. /**
  72450. * Attaches the effect on cameras
  72451. * @param cameras The camera to attach to.
  72452. */
  72453. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72454. var _this = this;
  72455. var cameraKey;
  72456. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72457. if (!cams) {
  72458. return;
  72459. }
  72460. for (var i = 0; i < cams.length; i++) {
  72461. var camera = cams[i];
  72462. var cameraName = camera.name;
  72463. if (this._singleInstance) {
  72464. cameraKey = 0;
  72465. }
  72466. else {
  72467. cameraKey = cameraName;
  72468. }
  72469. if (!this._postProcesses[cameraKey]) {
  72470. var postProcess = this._getPostProcesses();
  72471. if (postProcess) {
  72472. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72473. }
  72474. }
  72475. if (!this._indicesForCamera[cameraName]) {
  72476. this._indicesForCamera[cameraName] = [];
  72477. }
  72478. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72479. var index = camera.attachPostProcess(postProcess);
  72480. _this._indicesForCamera[cameraName].push(index);
  72481. });
  72482. if (!this._cameras[cameraName]) {
  72483. this._cameras[cameraName] = camera;
  72484. }
  72485. }
  72486. };
  72487. /**
  72488. * Detatches the effect on cameras
  72489. * @param cameras The camera to detatch from.
  72490. */
  72491. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72492. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72493. if (!cams) {
  72494. return;
  72495. }
  72496. for (var i = 0; i < cams.length; i++) {
  72497. var camera = cams[i];
  72498. var cameraName = camera.name;
  72499. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72500. camera.detachPostProcess(postProcess);
  72501. });
  72502. if (this._cameras[cameraName]) {
  72503. //this._indicesForCamera.splice(index, 1);
  72504. this._cameras[cameraName] = null;
  72505. }
  72506. }
  72507. };
  72508. /**
  72509. * Enables the effect on given cameras
  72510. * @param cameras The camera to enable.
  72511. */
  72512. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72513. var _this = this;
  72514. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72515. if (!cams) {
  72516. return;
  72517. }
  72518. for (var i = 0; i < cams.length; i++) {
  72519. var camera = cams[i];
  72520. var cameraName = camera.name;
  72521. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72522. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72523. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72524. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72525. });
  72526. }
  72527. }
  72528. }
  72529. };
  72530. /**
  72531. * Disables the effect on the given cameras
  72532. * @param cameras The camera to disable.
  72533. */
  72534. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72535. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72536. if (!cams) {
  72537. return;
  72538. }
  72539. for (var i = 0; i < cams.length; i++) {
  72540. var camera = cams[i];
  72541. var cameraName = camera.name;
  72542. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72543. camera.detachPostProcess(postProcess);
  72544. });
  72545. }
  72546. };
  72547. /**
  72548. * Gets a list of the post processes contained in the effect.
  72549. * @param camera The camera to get the post processes on.
  72550. * @returns The list of the post processes in the effect.
  72551. */
  72552. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72553. if (this._singleInstance) {
  72554. return this._postProcesses[0];
  72555. }
  72556. else {
  72557. if (!camera) {
  72558. return null;
  72559. }
  72560. return this._postProcesses[camera.name];
  72561. }
  72562. };
  72563. return PostProcessRenderEffect;
  72564. }());
  72565. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72566. })(BABYLON || (BABYLON = {}));
  72567. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72568. var BABYLON;
  72569. (function (BABYLON) {
  72570. var PostProcessRenderPipeline = /** @class */ (function () {
  72571. function PostProcessRenderPipeline(engine, name) {
  72572. this.engine = engine;
  72573. this._name = name;
  72574. this._renderEffects = {};
  72575. this._renderEffectsForIsolatedPass = new Array();
  72576. this._cameras = [];
  72577. }
  72578. PostProcessRenderPipeline.prototype.getClassName = function () {
  72579. return "PostProcessRenderPipeline";
  72580. };
  72581. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72582. get: function () {
  72583. for (var renderEffectName in this._renderEffects) {
  72584. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72585. if (!this._renderEffects[renderEffectName].isSupported) {
  72586. return false;
  72587. }
  72588. }
  72589. }
  72590. return true;
  72591. },
  72592. enumerable: true,
  72593. configurable: true
  72594. });
  72595. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72596. this._renderEffects[renderEffect._name] = renderEffect;
  72597. };
  72598. // private
  72599. PostProcessRenderPipeline.prototype._rebuild = function () {
  72600. };
  72601. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72602. var renderEffects = this._renderEffects[renderEffectName];
  72603. if (!renderEffects) {
  72604. return;
  72605. }
  72606. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72607. };
  72608. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72609. var renderEffects = this._renderEffects[renderEffectName];
  72610. if (!renderEffects) {
  72611. return;
  72612. }
  72613. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72614. };
  72615. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72616. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72617. if (!cams) {
  72618. return;
  72619. }
  72620. var indicesToDelete = [];
  72621. var i;
  72622. for (i = 0; i < cams.length; i++) {
  72623. var camera = cams[i];
  72624. var cameraName = camera.name;
  72625. if (this._cameras.indexOf(camera) === -1) {
  72626. this._cameras[cameraName] = camera;
  72627. }
  72628. else if (unique) {
  72629. indicesToDelete.push(i);
  72630. }
  72631. }
  72632. for (i = 0; i < indicesToDelete.length; i++) {
  72633. cameras.splice(indicesToDelete[i], 1);
  72634. }
  72635. for (var renderEffectName in this._renderEffects) {
  72636. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72637. this._renderEffects[renderEffectName]._attachCameras(cams);
  72638. }
  72639. }
  72640. };
  72641. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72642. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72643. if (!cams) {
  72644. return;
  72645. }
  72646. for (var renderEffectName in this._renderEffects) {
  72647. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72648. this._renderEffects[renderEffectName]._detachCameras(cams);
  72649. }
  72650. }
  72651. for (var i = 0; i < cams.length; i++) {
  72652. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72653. }
  72654. };
  72655. PostProcessRenderPipeline.prototype._update = function () {
  72656. for (var renderEffectName in this._renderEffects) {
  72657. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72658. this._renderEffects[renderEffectName]._update();
  72659. }
  72660. }
  72661. for (var i = 0; i < this._cameras.length; i++) {
  72662. var cameraName = this._cameras[i].name;
  72663. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72664. this._renderEffectsForIsolatedPass[cameraName]._update();
  72665. }
  72666. }
  72667. };
  72668. PostProcessRenderPipeline.prototype._reset = function () {
  72669. this._renderEffects = {};
  72670. this._renderEffectsForIsolatedPass = new Array();
  72671. };
  72672. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72673. // 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)
  72674. var effectKeys = Object.keys(this._renderEffects);
  72675. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72676. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72677. if (postProcesses) {
  72678. postProcesses[0].samples = sampleCount;
  72679. return true;
  72680. }
  72681. }
  72682. return false;
  72683. };
  72684. PostProcessRenderPipeline.prototype.dispose = function () {
  72685. // Must be implemented by children
  72686. };
  72687. __decorate([
  72688. BABYLON.serialize()
  72689. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72690. return PostProcessRenderPipeline;
  72691. }());
  72692. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72693. })(BABYLON || (BABYLON = {}));
  72694. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72695. var BABYLON;
  72696. (function (BABYLON) {
  72697. /**
  72698. * This represents a depth renderer in Babylon.
  72699. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72700. */
  72701. var DepthRenderer = /** @class */ (function () {
  72702. /**
  72703. * Instantiates a depth renderer
  72704. * @param scene The scene the renderer belongs to
  72705. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72706. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72707. */
  72708. function DepthRenderer(scene, type, camera) {
  72709. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72710. if (camera === void 0) { camera = null; }
  72711. var _this = this;
  72712. this._scene = scene;
  72713. this._camera = camera;
  72714. var engine = scene.getEngine();
  72715. // Render target
  72716. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72717. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72718. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72719. this._depthMap.refreshRate = 1;
  72720. this._depthMap.renderParticles = false;
  72721. this._depthMap.renderList = null;
  72722. // Camera to get depth map from to support multiple concurrent cameras
  72723. this._depthMap.activeCamera = this._camera;
  72724. this._depthMap.ignoreCameraViewport = true;
  72725. this._depthMap.useCameraPostProcesses = false;
  72726. // set default depth value to 1.0 (far away)
  72727. this._depthMap.onClearObservable.add(function (engine) {
  72728. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72729. });
  72730. // Custom render function
  72731. var renderSubMesh = function (subMesh) {
  72732. var mesh = subMesh.getRenderingMesh();
  72733. var scene = _this._scene;
  72734. var engine = scene.getEngine();
  72735. var material = subMesh.getMaterial();
  72736. if (!material) {
  72737. return;
  72738. }
  72739. // Culling and reverse (right handed system)
  72740. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72741. // Managing instances
  72742. var batch = mesh._getInstancesRenderList(subMesh._id);
  72743. if (batch.mustReturn) {
  72744. return;
  72745. }
  72746. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72747. var camera = _this._camera || scene.activeCamera;
  72748. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72749. engine.enableEffect(_this._effect);
  72750. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72751. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72752. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72753. // Alpha test
  72754. if (material && material.needAlphaTesting()) {
  72755. var alphaTexture = material.getAlphaTestTexture();
  72756. if (alphaTexture) {
  72757. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72758. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72759. }
  72760. }
  72761. // Bones
  72762. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72763. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72764. }
  72765. // Draw
  72766. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72767. }
  72768. };
  72769. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72770. var index;
  72771. if (depthOnlySubMeshes.length) {
  72772. engine.setColorWrite(false);
  72773. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72774. renderSubMesh(depthOnlySubMeshes.data[index]);
  72775. }
  72776. engine.setColorWrite(true);
  72777. }
  72778. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72779. renderSubMesh(opaqueSubMeshes.data[index]);
  72780. }
  72781. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72782. renderSubMesh(alphaTestSubMeshes.data[index]);
  72783. }
  72784. };
  72785. }
  72786. /**
  72787. * Creates the depth rendering effect and checks if the effect is ready.
  72788. * @param subMesh The submesh to be used to render the depth map of
  72789. * @param useInstances If multiple world instances should be used
  72790. * @returns if the depth renderer is ready to render the depth map
  72791. */
  72792. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72793. var material = subMesh.getMaterial();
  72794. if (material.disableDepthWrite) {
  72795. return false;
  72796. }
  72797. var defines = [];
  72798. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72799. var mesh = subMesh.getMesh();
  72800. // Alpha test
  72801. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72802. defines.push("#define ALPHATEST");
  72803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72804. attribs.push(BABYLON.VertexBuffer.UVKind);
  72805. defines.push("#define UV1");
  72806. }
  72807. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72808. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72809. defines.push("#define UV2");
  72810. }
  72811. }
  72812. // Bones
  72813. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72814. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72815. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72816. if (mesh.numBoneInfluencers > 4) {
  72817. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72818. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72819. }
  72820. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72821. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72822. }
  72823. else {
  72824. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72825. }
  72826. // Instances
  72827. if (useInstances) {
  72828. defines.push("#define INSTANCES");
  72829. attribs.push("world0");
  72830. attribs.push("world1");
  72831. attribs.push("world2");
  72832. attribs.push("world3");
  72833. }
  72834. // Get correct effect
  72835. var join = defines.join("\n");
  72836. if (this._cachedDefines !== join) {
  72837. this._cachedDefines = join;
  72838. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72839. }
  72840. return this._effect.isReady();
  72841. };
  72842. /**
  72843. * Gets the texture which the depth map will be written to.
  72844. * @returns The depth map texture
  72845. */
  72846. DepthRenderer.prototype.getDepthMap = function () {
  72847. return this._depthMap;
  72848. };
  72849. /**
  72850. * Disposes of the depth renderer.
  72851. */
  72852. DepthRenderer.prototype.dispose = function () {
  72853. this._depthMap.dispose();
  72854. };
  72855. return DepthRenderer;
  72856. }());
  72857. BABYLON.DepthRenderer = DepthRenderer;
  72858. })(BABYLON || (BABYLON = {}));
  72859. //# sourceMappingURL=babylon.depthRenderer.js.map
  72860. var BABYLON;
  72861. (function (BABYLON) {
  72862. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72863. __extends(SSAORenderingPipeline, _super);
  72864. /**
  72865. * @constructor
  72866. * @param {string} name - The rendering pipeline name
  72867. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72868. * @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 }
  72869. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72870. */
  72871. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72872. var _this = _super.call(this, scene.getEngine(), name) || this;
  72873. // Members
  72874. /**
  72875. * The PassPostProcess id in the pipeline that contains the original scene color
  72876. */
  72877. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72878. /**
  72879. * The SSAO PostProcess id in the pipeline
  72880. */
  72881. _this.SSAORenderEffect = "SSAORenderEffect";
  72882. /**
  72883. * The horizontal blur PostProcess id in the pipeline
  72884. */
  72885. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72886. /**
  72887. * The vertical blur PostProcess id in the pipeline
  72888. */
  72889. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72890. /**
  72891. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72892. */
  72893. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72894. /**
  72895. * The output strength of the SSAO post-process. Default value is 1.0.
  72896. */
  72897. _this.totalStrength = 1.0;
  72898. /**
  72899. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72900. */
  72901. _this.radius = 0.0001;
  72902. /**
  72903. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72904. * Must not be equal to fallOff and superior to fallOff.
  72905. * Default value is 0.975
  72906. */
  72907. _this.area = 0.0075;
  72908. /**
  72909. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72910. * Must not be equal to area and inferior to area.
  72911. * Default value is 0.0
  72912. */
  72913. _this.fallOff = 0.000001;
  72914. /**
  72915. * The base color of the SSAO post-process
  72916. * The final result is "base + ssao" between [0, 1]
  72917. */
  72918. _this.base = 0.5;
  72919. _this._firstUpdate = true;
  72920. _this._scene = scene;
  72921. // Set up assets
  72922. _this._createRandomTexture();
  72923. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72924. var ssaoRatio = ratio.ssaoRatio || ratio;
  72925. var combineRatio = ratio.combineRatio || ratio;
  72926. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72927. _this._createSSAOPostProcess(ssaoRatio);
  72928. _this._createBlurPostProcess(ssaoRatio);
  72929. _this._createSSAOCombinePostProcess(combineRatio);
  72930. // Set up pipeline
  72931. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72932. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72933. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72934. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72935. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72936. // Finish
  72937. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72938. if (cameras)
  72939. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72940. return _this;
  72941. }
  72942. // Public Methods
  72943. /**
  72944. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72945. */
  72946. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72947. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72948. for (var i = 0; i < this._scene.cameras.length; i++) {
  72949. var camera = this._scene.cameras[i];
  72950. this._originalColorPostProcess.dispose(camera);
  72951. this._ssaoPostProcess.dispose(camera);
  72952. this._blurHPostProcess.dispose(camera);
  72953. this._blurVPostProcess.dispose(camera);
  72954. this._ssaoCombinePostProcess.dispose(camera);
  72955. }
  72956. this._randomTexture.dispose();
  72957. if (disableDepthRender)
  72958. this._scene.disableDepthRenderer();
  72959. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72960. _super.prototype.dispose.call(this);
  72961. };
  72962. // Private Methods
  72963. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72964. var _this = this;
  72965. var size = 16;
  72966. 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);
  72967. 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);
  72968. this._blurHPostProcess.onActivateObservable.add(function () {
  72969. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72970. _this._blurHPostProcess.kernel = size * dw;
  72971. });
  72972. this._blurVPostProcess.onActivateObservable.add(function () {
  72973. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72974. _this._blurVPostProcess.kernel = size * dw;
  72975. });
  72976. };
  72977. SSAORenderingPipeline.prototype._rebuild = function () {
  72978. this._firstUpdate = true;
  72979. _super.prototype._rebuild.call(this);
  72980. };
  72981. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72982. var _this = this;
  72983. var numSamples = 16;
  72984. var sampleSphere = [
  72985. 0.5381, 0.1856, -0.4319,
  72986. 0.1379, 0.2486, 0.4430,
  72987. 0.3371, 0.5679, -0.0057,
  72988. -0.6999, -0.0451, -0.0019,
  72989. 0.0689, -0.1598, -0.8547,
  72990. 0.0560, 0.0069, -0.1843,
  72991. -0.0146, 0.1402, 0.0762,
  72992. 0.0100, -0.1924, -0.0344,
  72993. -0.3577, -0.5301, -0.4358,
  72994. -0.3169, 0.1063, 0.0158,
  72995. 0.0103, -0.5869, 0.0046,
  72996. -0.0897, -0.4940, 0.3287,
  72997. 0.7119, -0.0154, -0.0918,
  72998. -0.0533, 0.0596, -0.5411,
  72999. 0.0352, -0.0631, 0.5460,
  73000. -0.4776, 0.2847, -0.0271
  73001. ];
  73002. var samplesFactor = 1.0 / numSamples;
  73003. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73004. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73005. "area", "fallOff", "base", "range", "viewport"
  73006. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73007. this._ssaoPostProcess.onApply = function (effect) {
  73008. if (_this._firstUpdate) {
  73009. effect.setArray3("sampleSphere", sampleSphere);
  73010. effect.setFloat("samplesFactor", samplesFactor);
  73011. effect.setFloat("randTextureTiles", 4.0);
  73012. }
  73013. effect.setFloat("totalStrength", _this.totalStrength);
  73014. effect.setFloat("radius", _this.radius);
  73015. effect.setFloat("area", _this.area);
  73016. effect.setFloat("fallOff", _this.fallOff);
  73017. effect.setFloat("base", _this.base);
  73018. effect.setTexture("textureSampler", _this._depthTexture);
  73019. effect.setTexture("randomSampler", _this._randomTexture);
  73020. };
  73021. };
  73022. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73023. var _this = this;
  73024. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73025. this._ssaoCombinePostProcess.onApply = function (effect) {
  73026. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73027. };
  73028. };
  73029. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73030. var size = 512;
  73031. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73032. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73033. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73034. var context = this._randomTexture.getContext();
  73035. var rand = function (min, max) {
  73036. return Math.random() * (max - min) + min;
  73037. };
  73038. var randVector = BABYLON.Vector3.Zero();
  73039. for (var x = 0; x < size; x++) {
  73040. for (var y = 0; y < size; y++) {
  73041. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73042. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73043. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73044. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73045. context.fillRect(x, y, 1, 1);
  73046. }
  73047. }
  73048. this._randomTexture.update(false);
  73049. };
  73050. __decorate([
  73051. BABYLON.serialize()
  73052. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73053. __decorate([
  73054. BABYLON.serialize()
  73055. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73056. __decorate([
  73057. BABYLON.serialize()
  73058. ], SSAORenderingPipeline.prototype, "area", void 0);
  73059. __decorate([
  73060. BABYLON.serialize()
  73061. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73062. __decorate([
  73063. BABYLON.serialize()
  73064. ], SSAORenderingPipeline.prototype, "base", void 0);
  73065. return SSAORenderingPipeline;
  73066. }(BABYLON.PostProcessRenderPipeline));
  73067. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73068. })(BABYLON || (BABYLON = {}));
  73069. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73070. var BABYLON;
  73071. (function (BABYLON) {
  73072. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73073. __extends(SSAO2RenderingPipeline, _super);
  73074. /**
  73075. * @constructor
  73076. * @param {string} name - The rendering pipeline name
  73077. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73078. * @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 }
  73079. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73080. */
  73081. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73082. var _this = _super.call(this, scene.getEngine(), name) || this;
  73083. // Members
  73084. /**
  73085. * The PassPostProcess id in the pipeline that contains the original scene color
  73086. */
  73087. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73088. /**
  73089. * The SSAO PostProcess id in the pipeline
  73090. */
  73091. _this.SSAORenderEffect = "SSAORenderEffect";
  73092. /**
  73093. * The horizontal blur PostProcess id in the pipeline
  73094. */
  73095. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73096. /**
  73097. * The vertical blur PostProcess id in the pipeline
  73098. */
  73099. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73100. /**
  73101. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73102. */
  73103. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73104. /**
  73105. * The output strength of the SSAO post-process. Default value is 1.0.
  73106. */
  73107. _this.totalStrength = 1.0;
  73108. /**
  73109. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73110. */
  73111. _this.maxZ = 100.0;
  73112. /**
  73113. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73114. */
  73115. _this.minZAspect = 0.2;
  73116. /**
  73117. * Number of samples used for the SSAO calculations. Default value is 8
  73118. */
  73119. _this._samples = 8;
  73120. /**
  73121. * Are we using bilateral blur ?
  73122. */
  73123. _this._expensiveBlur = true;
  73124. /**
  73125. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73126. */
  73127. _this.radius = 2.0;
  73128. /**
  73129. * The base color of the SSAO post-process
  73130. * The final result is "base + ssao" between [0, 1]
  73131. */
  73132. _this.base = 0.1;
  73133. _this._firstUpdate = true;
  73134. _this._scene = scene;
  73135. _this._ratio = ratio;
  73136. if (!_this.isSupported) {
  73137. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73138. return _this;
  73139. }
  73140. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73141. var blurRatio = _this._ratio.blurRatio || ratio;
  73142. // Set up assets
  73143. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73144. _this._createRandomTexture();
  73145. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73146. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73147. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73148. _this._createSSAOPostProcess(1.0);
  73149. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73150. _this._createSSAOCombinePostProcess(blurRatio);
  73151. // Set up pipeline
  73152. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73153. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73154. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73155. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73156. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73157. // Finish
  73158. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73159. if (cameras)
  73160. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73161. return _this;
  73162. }
  73163. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73164. get: function () {
  73165. return this._samples;
  73166. },
  73167. set: function (n) {
  73168. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73169. this._samples = n;
  73170. this._sampleSphere = this._generateHemisphere();
  73171. this._firstUpdate = true;
  73172. },
  73173. enumerable: true,
  73174. configurable: true
  73175. });
  73176. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73177. get: function () {
  73178. return this._expensiveBlur;
  73179. },
  73180. set: function (b) {
  73181. 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"]);
  73182. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73183. this._expensiveBlur = b;
  73184. this._firstUpdate = true;
  73185. },
  73186. enumerable: true,
  73187. configurable: true
  73188. });
  73189. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73190. /**
  73191. * Support test.
  73192. */
  73193. get: function () {
  73194. var engine = BABYLON.Engine.LastCreatedEngine;
  73195. if (!engine) {
  73196. return false;
  73197. }
  73198. return engine.getCaps().drawBuffersExtension;
  73199. },
  73200. enumerable: true,
  73201. configurable: true
  73202. });
  73203. // Public Methods
  73204. /**
  73205. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73206. */
  73207. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73208. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73209. for (var i = 0; i < this._scene.cameras.length; i++) {
  73210. var camera = this._scene.cameras[i];
  73211. this._originalColorPostProcess.dispose(camera);
  73212. this._ssaoPostProcess.dispose(camera);
  73213. this._blurHPostProcess.dispose(camera);
  73214. this._blurVPostProcess.dispose(camera);
  73215. this._ssaoCombinePostProcess.dispose(camera);
  73216. }
  73217. this._randomTexture.dispose();
  73218. if (disableGeometryBufferRenderer)
  73219. this._scene.disableGeometryBufferRenderer();
  73220. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73221. _super.prototype.dispose.call(this);
  73222. };
  73223. // Private Methods
  73224. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73225. var _this = this;
  73226. this._samplerOffsets = [];
  73227. var expensive = this.expensiveBlur;
  73228. for (var i = -8; i < 8; i++) {
  73229. this._samplerOffsets.push(i * 2 + 0.5);
  73230. }
  73231. 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");
  73232. this._blurHPostProcess.onApply = function (effect) {
  73233. if (!_this._scene.activeCamera) {
  73234. return;
  73235. }
  73236. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73237. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73238. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73239. effect.setFloat("radius", _this.radius);
  73240. effect.setTexture("depthSampler", _this._depthTexture);
  73241. if (_this._firstUpdate) {
  73242. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73243. }
  73244. };
  73245. 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");
  73246. this._blurVPostProcess.onApply = function (effect) {
  73247. if (!_this._scene.activeCamera) {
  73248. return;
  73249. }
  73250. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73251. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73252. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73253. effect.setFloat("radius", _this.radius);
  73254. effect.setTexture("depthSampler", _this._depthTexture);
  73255. if (_this._firstUpdate) {
  73256. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73257. _this._firstUpdate = false;
  73258. }
  73259. };
  73260. };
  73261. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73262. this._firstUpdate = true;
  73263. _super.prototype._rebuild.call(this);
  73264. };
  73265. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73266. var numSamples = this.samples;
  73267. var result = [];
  73268. var vector, scale;
  73269. var rand = function (min, max) {
  73270. return Math.random() * (max - min) + min;
  73271. };
  73272. var i = 0;
  73273. while (i < numSamples) {
  73274. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73275. vector.normalize();
  73276. scale = i / numSamples;
  73277. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73278. vector.scaleInPlace(scale);
  73279. result.push(vector.x, vector.y, vector.z);
  73280. i++;
  73281. }
  73282. return result;
  73283. };
  73284. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73285. var _this = this;
  73286. var numSamples = this.samples;
  73287. this._sampleSphere = this._generateHemisphere();
  73288. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73289. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73290. "base", "range", "projection", "near", "far", "texelSize",
  73291. "xViewport", "yViewport", "maxZ", "minZAspect"
  73292. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73293. this._ssaoPostProcess.onApply = function (effect) {
  73294. if (_this._firstUpdate) {
  73295. effect.setArray3("sampleSphere", _this._sampleSphere);
  73296. effect.setFloat("randTextureTiles", 4.0);
  73297. }
  73298. if (!_this._scene.activeCamera) {
  73299. return;
  73300. }
  73301. effect.setFloat("samplesFactor", 1 / _this.samples);
  73302. effect.setFloat("totalStrength", _this.totalStrength);
  73303. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73304. effect.setFloat("radius", _this.radius);
  73305. effect.setFloat("maxZ", _this.maxZ);
  73306. effect.setFloat("minZAspect", _this.minZAspect);
  73307. effect.setFloat("base", _this.base);
  73308. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73309. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73310. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73311. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73312. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73313. effect.setTexture("textureSampler", _this._depthTexture);
  73314. effect.setTexture("normalSampler", _this._normalTexture);
  73315. effect.setTexture("randomSampler", _this._randomTexture);
  73316. };
  73317. };
  73318. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73319. var _this = this;
  73320. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73321. this._ssaoCombinePostProcess.onApply = function (effect) {
  73322. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73323. };
  73324. };
  73325. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73326. var size = 512;
  73327. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73328. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73329. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73330. var context = this._randomTexture.getContext();
  73331. var rand = function (min, max) {
  73332. return Math.random() * (max - min) + min;
  73333. };
  73334. var randVector = BABYLON.Vector3.Zero();
  73335. for (var x = 0; x < size; x++) {
  73336. for (var y = 0; y < size; y++) {
  73337. randVector.x = rand(0.0, 1.0);
  73338. randVector.y = rand(0.0, 1.0);
  73339. randVector.z = 0.0;
  73340. randVector.normalize();
  73341. randVector.scaleInPlace(255);
  73342. randVector.x = Math.floor(randVector.x);
  73343. randVector.y = Math.floor(randVector.y);
  73344. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73345. context.fillRect(x, y, 1, 1);
  73346. }
  73347. }
  73348. this._randomTexture.update(false);
  73349. };
  73350. /**
  73351. * Serialize the rendering pipeline (Used when exporting)
  73352. * @returns the serialized object
  73353. */
  73354. SSAO2RenderingPipeline.prototype.serialize = function () {
  73355. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73356. serializationObject.customType = "SSAO2RenderingPipeline";
  73357. return serializationObject;
  73358. };
  73359. /**
  73360. * Parse the serialized pipeline
  73361. * @param source Source pipeline.
  73362. * @param scene The scene to load the pipeline to.
  73363. * @param rootUrl The URL of the serialized pipeline.
  73364. * @returns An instantiated pipeline from the serialized object.
  73365. */
  73366. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73367. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73368. };
  73369. __decorate([
  73370. BABYLON.serialize()
  73371. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73372. __decorate([
  73373. BABYLON.serialize()
  73374. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73375. __decorate([
  73376. BABYLON.serialize()
  73377. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73378. __decorate([
  73379. BABYLON.serialize("samples")
  73380. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73381. __decorate([
  73382. BABYLON.serialize()
  73383. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73384. __decorate([
  73385. BABYLON.serialize("expensiveBlur")
  73386. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73387. __decorate([
  73388. BABYLON.serialize()
  73389. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73390. __decorate([
  73391. BABYLON.serialize()
  73392. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73393. return SSAO2RenderingPipeline;
  73394. }(BABYLON.PostProcessRenderPipeline));
  73395. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73396. })(BABYLON || (BABYLON = {}));
  73397. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73398. // BABYLON.JS Chromatic Aberration GLSL Shader
  73399. // Author: Olivier Guyot
  73400. // Separates very slightly R, G and B colors on the edges of the screen
  73401. // Inspired by Francois Tarlier & Martins Upitis
  73402. var BABYLON;
  73403. (function (BABYLON) {
  73404. var LensRenderingPipeline = /** @class */ (function (_super) {
  73405. __extends(LensRenderingPipeline, _super);
  73406. /**
  73407. * @constructor
  73408. *
  73409. * Effect parameters are as follow:
  73410. * {
  73411. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73412. * edge_blur: number; // from 0 to x (1 for realism)
  73413. * distortion: number; // from 0 to x (1 for realism)
  73414. * grain_amount: number; // from 0 to 1
  73415. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73416. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73417. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73418. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73419. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73420. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73421. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73422. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73423. * }
  73424. * Note: if an effect parameter is unset, effect is disabled
  73425. *
  73426. * @param {string} name - The rendering pipeline name
  73427. * @param {object} parameters - An object containing all parameters (see above)
  73428. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73429. * @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)
  73430. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73431. */
  73432. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73433. if (ratio === void 0) { ratio = 1.0; }
  73434. var _this = _super.call(this, scene.getEngine(), name) || this;
  73435. // Lens effects can be of the following:
  73436. // - chromatic aberration (slight shift of RGB colors)
  73437. // - blur on the edge of the lens
  73438. // - lens distortion
  73439. // - depth-of-field blur & highlights enhancing
  73440. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73441. // - grain effect (noise or custom texture)
  73442. // Two additional texture samplers are needed:
  73443. // - depth map (for depth-of-field)
  73444. // - grain texture
  73445. /**
  73446. * The chromatic aberration PostProcess id in the pipeline
  73447. */
  73448. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73449. /**
  73450. * The highlights enhancing PostProcess id in the pipeline
  73451. */
  73452. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73453. /**
  73454. * The depth-of-field PostProcess id in the pipeline
  73455. */
  73456. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73457. _this._scene = scene;
  73458. // Fetch texture samplers
  73459. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73460. if (parameters.grain_texture) {
  73461. _this._grainTexture = parameters.grain_texture;
  73462. }
  73463. else {
  73464. _this._createGrainTexture();
  73465. }
  73466. // save parameters
  73467. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73468. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73469. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73470. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73471. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73472. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73473. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73474. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73475. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73476. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73477. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73478. // Create effects
  73479. _this._createChromaticAberrationPostProcess(ratio);
  73480. _this._createHighlightsPostProcess(ratio);
  73481. _this._createDepthOfFieldPostProcess(ratio / 4);
  73482. // Set up pipeline
  73483. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73484. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73485. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73486. if (_this._highlightsGain === -1) {
  73487. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73488. }
  73489. // Finish
  73490. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73491. if (cameras) {
  73492. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73493. }
  73494. return _this;
  73495. }
  73496. // public methods (self explanatory)
  73497. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73498. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73499. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73500. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73501. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73502. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73503. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73504. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73505. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73506. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73507. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73508. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73509. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73510. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73511. };
  73512. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73513. this._highlightsPostProcess.updateEffect();
  73514. };
  73515. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73516. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73517. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73518. this._highlightsGain = amount;
  73519. };
  73520. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73521. if (this._highlightsGain === -1) {
  73522. this._highlightsGain = 1.0;
  73523. }
  73524. this._highlightsThreshold = amount;
  73525. };
  73526. LensRenderingPipeline.prototype.disableHighlights = function () {
  73527. this._highlightsGain = -1;
  73528. };
  73529. /**
  73530. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73531. */
  73532. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73533. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73534. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73535. this._chromaticAberrationPostProcess = null;
  73536. this._highlightsPostProcess = null;
  73537. this._depthOfFieldPostProcess = null;
  73538. this._grainTexture.dispose();
  73539. if (disableDepthRender)
  73540. this._scene.disableDepthRenderer();
  73541. };
  73542. // colors shifting and distortion
  73543. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73544. var _this = this;
  73545. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73546. [], // samplers
  73547. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73548. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73549. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73550. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73551. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73552. effect.setFloat('radialIntensity', 1);
  73553. effect.setFloat2('direction', 17, 17);
  73554. effect.setFloat2('centerPosition', 0.5, 0.5);
  73555. };
  73556. };
  73557. // highlights enhancing
  73558. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73559. var _this = this;
  73560. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73561. [], // samplers
  73562. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73563. this._highlightsPostProcess.onApply = function (effect) {
  73564. effect.setFloat('gain', _this._highlightsGain);
  73565. effect.setFloat('threshold', _this._highlightsThreshold);
  73566. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73567. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73568. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73569. };
  73570. };
  73571. // colors shifting and distortion
  73572. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73573. var _this = this;
  73574. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73575. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73576. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73577. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73578. this._depthOfFieldPostProcess.onApply = function (effect) {
  73579. effect.setTexture("depthSampler", _this._depthTexture);
  73580. effect.setTexture("grainSampler", _this._grainTexture);
  73581. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73582. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73583. effect.setFloat('grain_amount', _this._grainAmount);
  73584. effect.setBool('blur_noise', _this._blurNoise);
  73585. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73586. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73587. effect.setFloat('distortion', _this._distortion);
  73588. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73589. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73590. effect.setFloat('aperture', _this._dofAperture);
  73591. effect.setFloat('darken', _this._dofDarken);
  73592. effect.setFloat('edge_blur', _this._edgeBlur);
  73593. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73594. if (_this._scene.activeCamera) {
  73595. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73596. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73597. }
  73598. };
  73599. };
  73600. // creates a black and white random noise texture, 512x512
  73601. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73602. var size = 512;
  73603. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73604. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73605. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73606. var context = this._grainTexture.getContext();
  73607. var rand = function (min, max) {
  73608. return Math.random() * (max - min) + min;
  73609. };
  73610. var value;
  73611. for (var x = 0; x < size; x++) {
  73612. for (var y = 0; y < size; y++) {
  73613. value = Math.floor(rand(0.42, 0.58) * 255);
  73614. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73615. context.fillRect(x, y, 1, 1);
  73616. }
  73617. }
  73618. this._grainTexture.update(false);
  73619. };
  73620. return LensRenderingPipeline;
  73621. }(BABYLON.PostProcessRenderPipeline));
  73622. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73623. })(BABYLON || (BABYLON = {}));
  73624. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73625. var BABYLON;
  73626. (function (BABYLON) {
  73627. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73628. __extends(StandardRenderingPipeline, _super);
  73629. /**
  73630. * @constructor
  73631. * @param {string} name - The rendering pipeline name
  73632. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73633. * @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)
  73634. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73635. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73636. */
  73637. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73638. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73639. var _this = _super.call(this, scene.getEngine(), name) || this;
  73640. _this.downSampleX4PostProcess = null;
  73641. _this.brightPassPostProcess = null;
  73642. _this.blurHPostProcesses = [];
  73643. _this.blurVPostProcesses = [];
  73644. _this.textureAdderPostProcess = null;
  73645. _this.volumetricLightPostProcess = null;
  73646. _this.volumetricLightSmoothXPostProcess = null;
  73647. _this.volumetricLightSmoothYPostProcess = null;
  73648. _this.volumetricLightMergePostProces = null;
  73649. _this.volumetricLightFinalPostProcess = null;
  73650. _this.luminancePostProcess = null;
  73651. _this.luminanceDownSamplePostProcesses = [];
  73652. _this.hdrPostProcess = null;
  73653. _this.textureAdderFinalPostProcess = null;
  73654. _this.lensFlareFinalPostProcess = null;
  73655. _this.hdrFinalPostProcess = null;
  73656. _this.lensFlarePostProcess = null;
  73657. _this.lensFlareComposePostProcess = null;
  73658. _this.motionBlurPostProcess = null;
  73659. _this.depthOfFieldPostProcess = null;
  73660. // Values
  73661. _this.brightThreshold = 1.0;
  73662. _this.blurWidth = 512.0;
  73663. _this.horizontalBlur = false;
  73664. _this.exposure = 1.0;
  73665. _this.lensTexture = null;
  73666. _this.volumetricLightCoefficient = 0.2;
  73667. _this.volumetricLightPower = 4.0;
  73668. _this.volumetricLightBlurScale = 64.0;
  73669. _this.sourceLight = null;
  73670. _this.hdrMinimumLuminance = 1.0;
  73671. _this.hdrDecreaseRate = 0.5;
  73672. _this.hdrIncreaseRate = 0.5;
  73673. _this.lensColorTexture = null;
  73674. _this.lensFlareStrength = 20.0;
  73675. _this.lensFlareGhostDispersal = 1.4;
  73676. _this.lensFlareHaloWidth = 0.7;
  73677. _this.lensFlareDistortionStrength = 16.0;
  73678. _this.lensStarTexture = null;
  73679. _this.lensFlareDirtTexture = null;
  73680. _this.depthOfFieldDistance = 10.0;
  73681. _this.depthOfFieldBlurWidth = 64.0;
  73682. _this.motionStrength = 1.0;
  73683. // IAnimatable
  73684. _this.animations = [];
  73685. _this._currentDepthOfFieldSource = null;
  73686. _this._hdrCurrentLuminance = 1.0;
  73687. // Getters and setters
  73688. _this._bloomEnabled = true;
  73689. _this._depthOfFieldEnabled = false;
  73690. _this._vlsEnabled = false;
  73691. _this._lensFlareEnabled = false;
  73692. _this._hdrEnabled = false;
  73693. _this._motionBlurEnabled = false;
  73694. _this._motionBlurSamples = 64.0;
  73695. _this._volumetricLightStepsCount = 50.0;
  73696. _this._cameras = cameras || [];
  73697. // Initialize
  73698. _this._scene = scene;
  73699. _this._basePostProcess = originalPostProcess;
  73700. _this._ratio = ratio;
  73701. // Misc
  73702. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73703. // Finish
  73704. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73705. _this._buildPipeline();
  73706. return _this;
  73707. }
  73708. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73709. get: function () {
  73710. return this._bloomEnabled;
  73711. },
  73712. set: function (enabled) {
  73713. if (this._bloomEnabled === enabled) {
  73714. return;
  73715. }
  73716. this._bloomEnabled = enabled;
  73717. this._buildPipeline();
  73718. },
  73719. enumerable: true,
  73720. configurable: true
  73721. });
  73722. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73723. get: function () {
  73724. return this._depthOfFieldEnabled;
  73725. },
  73726. set: function (enabled) {
  73727. if (this._depthOfFieldEnabled === enabled) {
  73728. return;
  73729. }
  73730. this._depthOfFieldEnabled = enabled;
  73731. this._buildPipeline();
  73732. },
  73733. enumerable: true,
  73734. configurable: true
  73735. });
  73736. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73737. get: function () {
  73738. return this._lensFlareEnabled;
  73739. },
  73740. set: function (enabled) {
  73741. if (this._lensFlareEnabled === enabled) {
  73742. return;
  73743. }
  73744. this._lensFlareEnabled = enabled;
  73745. this._buildPipeline();
  73746. },
  73747. enumerable: true,
  73748. configurable: true
  73749. });
  73750. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73751. get: function () {
  73752. return this._hdrEnabled;
  73753. },
  73754. set: function (enabled) {
  73755. if (this._hdrEnabled === enabled) {
  73756. return;
  73757. }
  73758. this._hdrEnabled = enabled;
  73759. this._buildPipeline();
  73760. },
  73761. enumerable: true,
  73762. configurable: true
  73763. });
  73764. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73765. get: function () {
  73766. return this._vlsEnabled;
  73767. },
  73768. set: function (enabled) {
  73769. if (this._vlsEnabled === enabled) {
  73770. return;
  73771. }
  73772. if (enabled) {
  73773. var geometry = this._scene.enableGeometryBufferRenderer();
  73774. if (!geometry) {
  73775. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73776. return;
  73777. }
  73778. }
  73779. this._vlsEnabled = enabled;
  73780. this._buildPipeline();
  73781. },
  73782. enumerable: true,
  73783. configurable: true
  73784. });
  73785. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73786. get: function () {
  73787. return this._motionBlurEnabled;
  73788. },
  73789. set: function (enabled) {
  73790. if (this._motionBlurEnabled === enabled) {
  73791. return;
  73792. }
  73793. this._motionBlurEnabled = enabled;
  73794. this._buildPipeline();
  73795. },
  73796. enumerable: true,
  73797. configurable: true
  73798. });
  73799. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73800. get: function () {
  73801. return this._volumetricLightStepsCount;
  73802. },
  73803. set: function (count) {
  73804. if (this.volumetricLightPostProcess) {
  73805. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73806. }
  73807. this._volumetricLightStepsCount = count;
  73808. },
  73809. enumerable: true,
  73810. configurable: true
  73811. });
  73812. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73813. get: function () {
  73814. return this._motionBlurSamples;
  73815. },
  73816. set: function (samples) {
  73817. if (this.motionBlurPostProcess) {
  73818. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73819. }
  73820. this._motionBlurSamples = samples;
  73821. },
  73822. enumerable: true,
  73823. configurable: true
  73824. });
  73825. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73826. var _this = this;
  73827. var ratio = this._ratio;
  73828. var scene = this._scene;
  73829. this._disposePostProcesses();
  73830. this._reset();
  73831. // Create pass post-process
  73832. if (!this._basePostProcess) {
  73833. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73834. this.originalPostProcess.onApply = function (effect) {
  73835. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73836. };
  73837. }
  73838. else {
  73839. this.originalPostProcess = this._basePostProcess;
  73840. }
  73841. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73842. this._currentDepthOfFieldSource = this.originalPostProcess;
  73843. if (this._bloomEnabled) {
  73844. // Create down sample X4 post-process
  73845. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73846. // Create bright pass post-process
  73847. this._createBrightPassPostProcess(scene, ratio / 2);
  73848. // Create gaussian blur post-processes (down sampling blurs)
  73849. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73850. // Create texture adder post-process
  73851. this._createTextureAdderPostProcess(scene, ratio);
  73852. // Create depth-of-field source post-process
  73853. 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);
  73854. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73855. }
  73856. if (this._vlsEnabled) {
  73857. // Create volumetric light
  73858. this._createVolumetricLightPostProcess(scene, ratio);
  73859. // Create volumetric light final post-process
  73860. 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);
  73861. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73862. }
  73863. if (this._lensFlareEnabled) {
  73864. // Create lens flare post-process
  73865. this._createLensFlarePostProcess(scene, ratio);
  73866. // Create depth-of-field source post-process post lens-flare and disable it now
  73867. 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);
  73868. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73869. }
  73870. if (this._hdrEnabled) {
  73871. // Create luminance
  73872. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73873. // Create HDR
  73874. this._createHdrPostProcess(scene, ratio);
  73875. // Create depth-of-field source post-process post hdr and disable it now
  73876. 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);
  73877. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73878. }
  73879. if (this._depthOfFieldEnabled) {
  73880. // Create gaussian blur used by depth-of-field
  73881. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73882. // Create depth-of-field post-process
  73883. this._createDepthOfFieldPostProcess(scene, ratio);
  73884. }
  73885. if (this._motionBlurEnabled) {
  73886. // Create motion blur post-process
  73887. this._createMotionBlurPostProcess(scene, ratio);
  73888. }
  73889. if (this._cameras !== null) {
  73890. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73891. }
  73892. };
  73893. // Down Sample X4 Post-Processs
  73894. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73895. var _this = this;
  73896. var downSampleX4Offsets = new Array(32);
  73897. 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);
  73898. this.downSampleX4PostProcess.onApply = function (effect) {
  73899. var id = 0;
  73900. var width = _this.downSampleX4PostProcess.width;
  73901. var height = _this.downSampleX4PostProcess.height;
  73902. for (var i = -2; i < 2; i++) {
  73903. for (var j = -2; j < 2; j++) {
  73904. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73905. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73906. id += 2;
  73907. }
  73908. }
  73909. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73910. };
  73911. // Add to pipeline
  73912. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73913. };
  73914. // Brightpass Post-Process
  73915. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73916. var _this = this;
  73917. var brightOffsets = new Array(8);
  73918. 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);
  73919. this.brightPassPostProcess.onApply = function (effect) {
  73920. var sU = (1.0 / _this.brightPassPostProcess.width);
  73921. var sV = (1.0 / _this.brightPassPostProcess.height);
  73922. brightOffsets[0] = -0.5 * sU;
  73923. brightOffsets[1] = 0.5 * sV;
  73924. brightOffsets[2] = 0.5 * sU;
  73925. brightOffsets[3] = 0.5 * sV;
  73926. brightOffsets[4] = -0.5 * sU;
  73927. brightOffsets[5] = -0.5 * sV;
  73928. brightOffsets[6] = 0.5 * sU;
  73929. brightOffsets[7] = -0.5 * sV;
  73930. effect.setArray2("dsOffsets", brightOffsets);
  73931. effect.setFloat("brightThreshold", _this.brightThreshold);
  73932. };
  73933. // Add to pipeline
  73934. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73935. };
  73936. // Create blur H&V post-processes
  73937. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73938. var _this = this;
  73939. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73940. var engine = scene.getEngine();
  73941. 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);
  73942. 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);
  73943. blurX.onActivateObservable.add(function () {
  73944. var dw = blurX.width / engine.getRenderWidth();
  73945. blurX.kernel = _this[blurWidthKey] * dw;
  73946. });
  73947. blurY.onActivateObservable.add(function () {
  73948. var dw = blurY.height / engine.getRenderHeight();
  73949. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73950. });
  73951. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73952. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73953. this.blurHPostProcesses.push(blurX);
  73954. this.blurVPostProcesses.push(blurY);
  73955. };
  73956. // Create texture adder post-process
  73957. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73958. var _this = this;
  73959. 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);
  73960. this.textureAdderPostProcess.onApply = function (effect) {
  73961. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73962. effect.setTexture("lensSampler", _this.lensTexture);
  73963. effect.setFloat("exposure", _this.exposure);
  73964. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73965. };
  73966. // Add to pipeline
  73967. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73968. };
  73969. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73970. var _this = this;
  73971. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73972. geometryRenderer.enablePosition = true;
  73973. var geometry = geometryRenderer.getGBuffer();
  73974. // Base post-process
  73975. 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));
  73976. var depthValues = BABYLON.Vector2.Zero();
  73977. this.volumetricLightPostProcess.onApply = function (effect) {
  73978. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73979. var generator = _this.sourceLight.getShadowGenerator();
  73980. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73981. effect.setTexture("positionSampler", geometry.textures[2]);
  73982. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73983. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73984. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73985. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73986. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73987. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73988. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73989. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73990. effect.setVector2("depthValues", depthValues);
  73991. }
  73992. };
  73993. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73994. // Smooth
  73995. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73996. // Merge
  73997. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73998. this.volumetricLightMergePostProces.onApply = function (effect) {
  73999. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74000. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74001. };
  74002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74003. };
  74004. // Create luminance
  74005. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74006. var _this = this;
  74007. // Create luminance
  74008. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74009. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74010. var offsets = [];
  74011. this.luminancePostProcess.onApply = function (effect) {
  74012. var sU = (1.0 / _this.luminancePostProcess.width);
  74013. var sV = (1.0 / _this.luminancePostProcess.height);
  74014. offsets[0] = -0.5 * sU;
  74015. offsets[1] = 0.5 * sV;
  74016. offsets[2] = 0.5 * sU;
  74017. offsets[3] = 0.5 * sV;
  74018. offsets[4] = -0.5 * sU;
  74019. offsets[5] = -0.5 * sV;
  74020. offsets[6] = 0.5 * sU;
  74021. offsets[7] = -0.5 * sV;
  74022. effect.setArray2("lumOffsets", offsets);
  74023. };
  74024. // Add to pipeline
  74025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74026. // Create down sample luminance
  74027. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74028. var size = Math.pow(3, i);
  74029. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74030. if (i === 0) {
  74031. defines += "#define FINAL_DOWN_SAMPLER";
  74032. }
  74033. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74034. this.luminanceDownSamplePostProcesses.push(postProcess);
  74035. }
  74036. // Create callbacks and add effects
  74037. var lastLuminance = this.luminancePostProcess;
  74038. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74039. var downSampleOffsets = new Array(18);
  74040. pp.onApply = function (effect) {
  74041. if (!lastLuminance) {
  74042. return;
  74043. }
  74044. var id = 0;
  74045. for (var x = -1; x < 2; x++) {
  74046. for (var y = -1; y < 2; y++) {
  74047. downSampleOffsets[id] = x / lastLuminance.width;
  74048. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74049. id += 2;
  74050. }
  74051. }
  74052. effect.setArray2("dsOffsets", downSampleOffsets);
  74053. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74054. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74055. lastLuminance = _this.luminancePostProcess;
  74056. }
  74057. else {
  74058. lastLuminance = pp;
  74059. }
  74060. };
  74061. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74062. pp.onAfterRender = function (effect) {
  74063. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74064. 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);
  74065. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74066. };
  74067. }
  74068. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74069. });
  74070. };
  74071. // Create HDR post-process
  74072. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74073. var _this = this;
  74074. 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);
  74075. var outputLiminance = 1;
  74076. var time = 0;
  74077. var lastTime = 0;
  74078. this.hdrPostProcess.onApply = function (effect) {
  74079. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74080. time += scene.getEngine().getDeltaTime();
  74081. if (outputLiminance < 0) {
  74082. outputLiminance = _this._hdrCurrentLuminance;
  74083. }
  74084. else {
  74085. var dt = (lastTime - time) / 1000.0;
  74086. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74087. outputLiminance += _this.hdrDecreaseRate * dt;
  74088. }
  74089. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74090. outputLiminance -= _this.hdrIncreaseRate * dt;
  74091. }
  74092. else {
  74093. outputLiminance = _this._hdrCurrentLuminance;
  74094. }
  74095. }
  74096. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74097. effect.setFloat("averageLuminance", outputLiminance);
  74098. lastTime = time;
  74099. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74100. };
  74101. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74102. };
  74103. // Create lens flare post-process
  74104. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74105. var _this = this;
  74106. 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);
  74107. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74108. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74109. 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);
  74110. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74111. var resolution = new BABYLON.Vector2(0, 0);
  74112. // Lens flare
  74113. this.lensFlarePostProcess.onApply = function (effect) {
  74114. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74115. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74116. effect.setFloat("strength", _this.lensFlareStrength);
  74117. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74118. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74119. // Shift
  74120. resolution.x = _this.lensFlarePostProcess.width;
  74121. resolution.y = _this.lensFlarePostProcess.height;
  74122. effect.setVector2("resolution", resolution);
  74123. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74124. };
  74125. // Compose
  74126. 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);
  74127. 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);
  74128. this.lensFlareComposePostProcess.onApply = function (effect) {
  74129. if (!_this._scene.activeCamera) {
  74130. return;
  74131. }
  74132. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74133. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74134. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74135. // Lens start rotation matrix
  74136. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74137. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74138. 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));
  74139. camRot *= 4.0;
  74140. 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);
  74141. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74142. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74143. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74144. };
  74145. };
  74146. // Create depth-of-field post-process
  74147. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74148. var _this = this;
  74149. 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);
  74150. this.depthOfFieldPostProcess.onApply = function (effect) {
  74151. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74152. effect.setTexture("depthSampler", _this._getDepthTexture());
  74153. effect.setFloat("distance", _this.depthOfFieldDistance);
  74154. };
  74155. // Add to pipeline
  74156. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74157. };
  74158. // Create motion blur post-process
  74159. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74160. var _this = this;
  74161. 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);
  74162. var motionScale = 0;
  74163. var prevViewProjection = BABYLON.Matrix.Identity();
  74164. var invViewProjection = BABYLON.Matrix.Identity();
  74165. var viewProjection = BABYLON.Matrix.Identity();
  74166. var screenSize = BABYLON.Vector2.Zero();
  74167. this.motionBlurPostProcess.onApply = function (effect) {
  74168. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74169. viewProjection.invertToRef(invViewProjection);
  74170. effect.setMatrix("inverseViewProjection", invViewProjection);
  74171. effect.setMatrix("prevViewProjection", prevViewProjection);
  74172. prevViewProjection = viewProjection;
  74173. screenSize.x = _this.motionBlurPostProcess.width;
  74174. screenSize.y = _this.motionBlurPostProcess.height;
  74175. effect.setVector2("screenSize", screenSize);
  74176. motionScale = scene.getEngine().getFps() / 60.0;
  74177. effect.setFloat("motionScale", motionScale);
  74178. effect.setFloat("motionStrength", _this.motionStrength);
  74179. effect.setTexture("depthSampler", _this._getDepthTexture());
  74180. };
  74181. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74182. };
  74183. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74184. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74185. var renderer = this._scene.enableGeometryBufferRenderer();
  74186. return renderer.getGBuffer().textures[0];
  74187. }
  74188. return this._scene.enableDepthRenderer().getDepthMap();
  74189. };
  74190. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74191. for (var i = 0; i < this._cameras.length; i++) {
  74192. var camera = this._cameras[i];
  74193. if (this.originalPostProcess) {
  74194. this.originalPostProcess.dispose(camera);
  74195. }
  74196. if (this.downSampleX4PostProcess) {
  74197. this.downSampleX4PostProcess.dispose(camera);
  74198. }
  74199. if (this.brightPassPostProcess) {
  74200. this.brightPassPostProcess.dispose(camera);
  74201. }
  74202. if (this.textureAdderPostProcess) {
  74203. this.textureAdderPostProcess.dispose(camera);
  74204. }
  74205. if (this.textureAdderFinalPostProcess) {
  74206. this.textureAdderFinalPostProcess.dispose(camera);
  74207. }
  74208. if (this.volumetricLightPostProcess) {
  74209. this.volumetricLightPostProcess.dispose(camera);
  74210. }
  74211. if (this.volumetricLightSmoothXPostProcess) {
  74212. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74213. }
  74214. if (this.volumetricLightSmoothYPostProcess) {
  74215. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74216. }
  74217. if (this.volumetricLightMergePostProces) {
  74218. this.volumetricLightMergePostProces.dispose(camera);
  74219. }
  74220. if (this.volumetricLightFinalPostProcess) {
  74221. this.volumetricLightFinalPostProcess.dispose(camera);
  74222. }
  74223. if (this.lensFlarePostProcess) {
  74224. this.lensFlarePostProcess.dispose(camera);
  74225. }
  74226. if (this.lensFlareComposePostProcess) {
  74227. this.lensFlareComposePostProcess.dispose(camera);
  74228. }
  74229. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74230. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74231. }
  74232. if (this.luminancePostProcess) {
  74233. this.luminancePostProcess.dispose(camera);
  74234. }
  74235. if (this.hdrPostProcess) {
  74236. this.hdrPostProcess.dispose(camera);
  74237. }
  74238. if (this.hdrFinalPostProcess) {
  74239. this.hdrFinalPostProcess.dispose(camera);
  74240. }
  74241. if (this.depthOfFieldPostProcess) {
  74242. this.depthOfFieldPostProcess.dispose(camera);
  74243. }
  74244. if (this.motionBlurPostProcess) {
  74245. this.motionBlurPostProcess.dispose(camera);
  74246. }
  74247. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74248. this.blurHPostProcesses[j].dispose(camera);
  74249. }
  74250. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74251. this.blurVPostProcesses[j].dispose(camera);
  74252. }
  74253. }
  74254. this.originalPostProcess = null;
  74255. this.downSampleX4PostProcess = null;
  74256. this.brightPassPostProcess = null;
  74257. this.textureAdderPostProcess = null;
  74258. this.textureAdderFinalPostProcess = null;
  74259. this.volumetricLightPostProcess = null;
  74260. this.volumetricLightSmoothXPostProcess = null;
  74261. this.volumetricLightSmoothYPostProcess = null;
  74262. this.volumetricLightMergePostProces = null;
  74263. this.volumetricLightFinalPostProcess = null;
  74264. this.lensFlarePostProcess = null;
  74265. this.lensFlareComposePostProcess = null;
  74266. this.luminancePostProcess = null;
  74267. this.hdrPostProcess = null;
  74268. this.hdrFinalPostProcess = null;
  74269. this.depthOfFieldPostProcess = null;
  74270. this.motionBlurPostProcess = null;
  74271. this.luminanceDownSamplePostProcesses = [];
  74272. this.blurHPostProcesses = [];
  74273. this.blurVPostProcesses = [];
  74274. };
  74275. /**
  74276. * Dispose of the pipeline and stop all post processes
  74277. */
  74278. StandardRenderingPipeline.prototype.dispose = function () {
  74279. this._disposePostProcesses();
  74280. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74281. _super.prototype.dispose.call(this);
  74282. };
  74283. /**
  74284. * Serialize the rendering pipeline (Used when exporting)
  74285. * @returns the serialized object
  74286. */
  74287. StandardRenderingPipeline.prototype.serialize = function () {
  74288. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74289. if (this.sourceLight) {
  74290. serializationObject.sourceLightId = this.sourceLight.id;
  74291. }
  74292. serializationObject.customType = "StandardRenderingPipeline";
  74293. return serializationObject;
  74294. };
  74295. /**
  74296. * Parse the serialized pipeline
  74297. * @param source Source pipeline.
  74298. * @param scene The scene to load the pipeline to.
  74299. * @param rootUrl The URL of the serialized pipeline.
  74300. * @returns An instantiated pipeline from the serialized object.
  74301. */
  74302. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74303. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74304. if (source.sourceLightId) {
  74305. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74306. }
  74307. return p;
  74308. };
  74309. // Luminance steps
  74310. StandardRenderingPipeline.LuminanceSteps = 6;
  74311. __decorate([
  74312. BABYLON.serialize()
  74313. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74314. __decorate([
  74315. BABYLON.serialize()
  74316. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74317. __decorate([
  74318. BABYLON.serialize()
  74319. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74320. __decorate([
  74321. BABYLON.serialize()
  74322. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74323. __decorate([
  74324. BABYLON.serializeAsTexture("lensTexture")
  74325. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74326. __decorate([
  74327. BABYLON.serialize()
  74328. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74329. __decorate([
  74330. BABYLON.serialize()
  74331. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74332. __decorate([
  74333. BABYLON.serialize()
  74334. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74335. __decorate([
  74336. BABYLON.serialize()
  74337. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74338. __decorate([
  74339. BABYLON.serialize()
  74340. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74341. __decorate([
  74342. BABYLON.serialize()
  74343. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74344. __decorate([
  74345. BABYLON.serializeAsTexture("lensColorTexture")
  74346. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74347. __decorate([
  74348. BABYLON.serialize()
  74349. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74350. __decorate([
  74351. BABYLON.serialize()
  74352. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74353. __decorate([
  74354. BABYLON.serialize()
  74355. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74356. __decorate([
  74357. BABYLON.serialize()
  74358. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74359. __decorate([
  74360. BABYLON.serializeAsTexture("lensStarTexture")
  74361. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74362. __decorate([
  74363. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74364. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74365. __decorate([
  74366. BABYLON.serialize()
  74367. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74368. __decorate([
  74369. BABYLON.serialize()
  74370. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74371. __decorate([
  74372. BABYLON.serialize()
  74373. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74374. __decorate([
  74375. BABYLON.serialize()
  74376. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74377. __decorate([
  74378. BABYLON.serialize()
  74379. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74380. __decorate([
  74381. BABYLON.serialize()
  74382. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74383. __decorate([
  74384. BABYLON.serialize()
  74385. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74386. __decorate([
  74387. BABYLON.serialize()
  74388. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74389. __decorate([
  74390. BABYLON.serialize()
  74391. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74392. __decorate([
  74393. BABYLON.serialize()
  74394. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74395. __decorate([
  74396. BABYLON.serialize()
  74397. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74398. __decorate([
  74399. BABYLON.serialize()
  74400. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74401. return StandardRenderingPipeline;
  74402. }(BABYLON.PostProcessRenderPipeline));
  74403. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74404. })(BABYLON || (BABYLON = {}));
  74405. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74406. var BABYLON;
  74407. (function (BABYLON) {
  74408. var FxaaPostProcess = /** @class */ (function (_super) {
  74409. __extends(FxaaPostProcess, _super);
  74410. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74411. if (camera === void 0) { camera = null; }
  74412. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74413. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  74414. _this.onApplyObservable.add(function (effect) {
  74415. var texelSize = _this.texelSize;
  74416. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74417. });
  74418. return _this;
  74419. }
  74420. return FxaaPostProcess;
  74421. }(BABYLON.PostProcess));
  74422. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74423. })(BABYLON || (BABYLON = {}));
  74424. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74425. var BABYLON;
  74426. (function (BABYLON) {
  74427. /**
  74428. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74429. */
  74430. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74431. __extends(ChromaticAberrationPostProcess, _super);
  74432. /**
  74433. * Creates a new instance ChromaticAberrationPostProcess
  74434. * @param name The name of the effect.
  74435. * @param screenWidth The width of the screen to apply the effect on.
  74436. * @param screenHeight The height of the screen to apply the effect on.
  74437. * @param options The required width/height ratio to downsize to before computing the render pass.
  74438. * @param camera The camera to apply the render pass to.
  74439. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74440. * @param engine The engine which the post process will be applied. (default: current engine)
  74441. * @param reusable If the post process can be reused on the same frame. (default: false)
  74442. * @param textureType Type of textures used when performing the post process. (default: 0)
  74443. * @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)
  74444. */
  74445. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74446. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74447. if (blockCompilation === void 0) { blockCompilation = false; }
  74448. 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;
  74449. /**
  74450. * The amount of seperation of rgb channels (default: 30)
  74451. */
  74452. _this.aberrationAmount = 30;
  74453. /**
  74454. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74455. */
  74456. _this.radialIntensity = 0;
  74457. /**
  74458. * 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))
  74459. */
  74460. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74461. /**
  74462. * 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))
  74463. */
  74464. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74465. _this.onApplyObservable.add(function (effect) {
  74466. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74467. effect.setFloat('screen_width', screenWidth);
  74468. effect.setFloat('screen_height', screenHeight);
  74469. effect.setFloat('radialIntensity', _this.radialIntensity);
  74470. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74471. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74472. });
  74473. return _this;
  74474. }
  74475. return ChromaticAberrationPostProcess;
  74476. }(BABYLON.PostProcess));
  74477. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74478. })(BABYLON || (BABYLON = {}));
  74479. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74480. var BABYLON;
  74481. (function (BABYLON) {
  74482. /**
  74483. * The GrainPostProcess adds noise to the image at mid luminance levels
  74484. */
  74485. var GrainPostProcess = /** @class */ (function (_super) {
  74486. __extends(GrainPostProcess, _super);
  74487. /**
  74488. * Creates a new instance of @see GrainPostProcess
  74489. * @param name The name of the effect.
  74490. * @param options The required width/height ratio to downsize to before computing the render pass.
  74491. * @param camera The camera to apply the render pass to.
  74492. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74493. * @param engine The engine which the post process will be applied. (default: current engine)
  74494. * @param reusable If the post process can be reused on the same frame. (default: false)
  74495. * @param textureType Type of textures used when performing the post process. (default: 0)
  74496. * @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)
  74497. */
  74498. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74499. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74500. if (blockCompilation === void 0) { blockCompilation = false; }
  74501. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74502. /**
  74503. * The intensity of the grain added (default: 30)
  74504. */
  74505. _this.intensity = 30;
  74506. /**
  74507. * If the grain should be randomized on every frame
  74508. */
  74509. _this.animated = false;
  74510. _this.onApplyObservable.add(function (effect) {
  74511. effect.setFloat('intensity', _this.intensity);
  74512. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74513. });
  74514. return _this;
  74515. }
  74516. return GrainPostProcess;
  74517. }(BABYLON.PostProcess));
  74518. BABYLON.GrainPostProcess = GrainPostProcess;
  74519. })(BABYLON || (BABYLON = {}));
  74520. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74521. var BABYLON;
  74522. (function (BABYLON) {
  74523. /**
  74524. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74525. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74526. */
  74527. var SharpenPostProcess = /** @class */ (function (_super) {
  74528. __extends(SharpenPostProcess, _super);
  74529. /**
  74530. * Creates a new instance ConvolutionPostProcess
  74531. * @param name The name of the effect.
  74532. * @param options The required width/height ratio to downsize to before computing the render pass.
  74533. * @param camera The camera to apply the render pass to.
  74534. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74535. * @param engine The engine which the post process will be applied. (default: current engine)
  74536. * @param reusable If the post process can be reused on the same frame. (default: false)
  74537. * @param textureType Type of textures used when performing the post process. (default: 0)
  74538. * @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)
  74539. */
  74540. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74541. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74542. if (blockCompilation === void 0) { blockCompilation = false; }
  74543. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74544. /**
  74545. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74546. */
  74547. _this.colorAmount = 1.0;
  74548. /**
  74549. * How much sharpness should be applied (default: 0.3)
  74550. */
  74551. _this.edgeAmount = 0.3;
  74552. _this.onApply = function (effect) {
  74553. effect.setFloat2("screenSize", _this.width, _this.height);
  74554. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74555. };
  74556. return _this;
  74557. }
  74558. return SharpenPostProcess;
  74559. }(BABYLON.PostProcess));
  74560. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74561. })(BABYLON || (BABYLON = {}));
  74562. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74563. var BABYLON;
  74564. (function (BABYLON) {
  74565. /**
  74566. * The Blur Post Process which blurs an image based on a kernel and direction.
  74567. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74568. */
  74569. var BlurPostProcess = /** @class */ (function (_super) {
  74570. __extends(BlurPostProcess, _super);
  74571. /**
  74572. * Creates a new instance BlurPostProcess
  74573. * @param name The name of the effect.
  74574. * @param direction The direction in which to blur the image.
  74575. * @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.
  74576. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74577. * @param camera The camera to apply the render pass to.
  74578. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74579. * @param engine The engine which the post process will be applied. (default: current engine)
  74580. * @param reusable If the post process can be reused on the same frame. (default: false)
  74581. * @param textureType Type of textures used when performing the post process. (default: 0)
  74582. * @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)
  74583. */
  74584. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74585. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74586. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74587. if (defines === void 0) { defines = ""; }
  74588. if (blockCompilation === void 0) { blockCompilation = false; }
  74589. 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;
  74590. _this.direction = direction;
  74591. _this.blockCompilation = blockCompilation;
  74592. _this._packedFloat = false;
  74593. _this._staticDefines = "";
  74594. _this._staticDefines = defines;
  74595. _this.onApplyObservable.add(function (effect) {
  74596. if (_this._outputTexture) {
  74597. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74598. }
  74599. else {
  74600. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74601. }
  74602. });
  74603. _this.kernel = kernel;
  74604. return _this;
  74605. }
  74606. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74607. /**
  74608. * Gets the length in pixels of the blur sample region
  74609. */
  74610. get: function () {
  74611. return this._idealKernel;
  74612. },
  74613. /**
  74614. * Sets the length in pixels of the blur sample region
  74615. */
  74616. set: function (v) {
  74617. if (this._idealKernel === v) {
  74618. return;
  74619. }
  74620. v = Math.max(v, 1);
  74621. this._idealKernel = v;
  74622. this._kernel = this._nearestBestKernel(v);
  74623. if (!this.blockCompilation) {
  74624. this._updateParameters();
  74625. }
  74626. },
  74627. enumerable: true,
  74628. configurable: true
  74629. });
  74630. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74631. /**
  74632. * Gets wether or not the blur is unpacking/repacking floats
  74633. */
  74634. get: function () {
  74635. return this._packedFloat;
  74636. },
  74637. /**
  74638. * Sets wether or not the blur needs to unpack/repack floats
  74639. */
  74640. set: function (v) {
  74641. if (this._packedFloat === v) {
  74642. return;
  74643. }
  74644. this._packedFloat = v;
  74645. if (!this.blockCompilation) {
  74646. this._updateParameters();
  74647. }
  74648. },
  74649. enumerable: true,
  74650. configurable: true
  74651. });
  74652. /**
  74653. * Updates the effect with the current post process compile time values and recompiles the shader.
  74654. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74655. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74656. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74657. * @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
  74658. * @param onCompiled Called when the shader has been compiled.
  74659. * @param onError Called if there is an error when compiling a shader.
  74660. */
  74661. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74662. if (defines === void 0) { defines = null; }
  74663. if (uniforms === void 0) { uniforms = null; }
  74664. if (samplers === void 0) { samplers = null; }
  74665. this._updateParameters(onCompiled, onError);
  74666. };
  74667. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74668. // Generate sampling offsets and weights
  74669. var N = this._kernel;
  74670. var centerIndex = (N - 1) / 2;
  74671. // Generate Gaussian sampling weights over kernel
  74672. var offsets = [];
  74673. var weights = [];
  74674. var totalWeight = 0;
  74675. for (var i = 0; i < N; i++) {
  74676. var u = i / (N - 1);
  74677. var w = this._gaussianWeight(u * 2.0 - 1);
  74678. offsets[i] = (i - centerIndex);
  74679. weights[i] = w;
  74680. totalWeight += w;
  74681. }
  74682. // Normalize weights
  74683. for (var i = 0; i < weights.length; i++) {
  74684. weights[i] /= totalWeight;
  74685. }
  74686. // Optimize: combine samples to take advantage of hardware linear sampling
  74687. // Walk from left to center, combining pairs (symmetrically)
  74688. var linearSamplingWeights = [];
  74689. var linearSamplingOffsets = [];
  74690. var linearSamplingMap = [];
  74691. for (var i = 0; i <= centerIndex; i += 2) {
  74692. var j = Math.min(i + 1, Math.floor(centerIndex));
  74693. var singleCenterSample = i === j;
  74694. if (singleCenterSample) {
  74695. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74696. }
  74697. else {
  74698. var sharedCell = j === centerIndex;
  74699. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74700. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74701. if (offsetLinear === 0) {
  74702. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74703. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74704. }
  74705. else {
  74706. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74707. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74708. }
  74709. }
  74710. }
  74711. for (var i = 0; i < linearSamplingMap.length; i++) {
  74712. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74713. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74714. }
  74715. // Replace with optimized
  74716. offsets = linearSamplingOffsets;
  74717. weights = linearSamplingWeights;
  74718. // Generate shaders
  74719. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74720. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74721. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74722. var defines = "";
  74723. defines += this._staticDefines;
  74724. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74725. if (this._staticDefines.indexOf("DOF") != -1) {
  74726. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74727. varyingCount--;
  74728. }
  74729. for (var i = 0; i < varyingCount; i++) {
  74730. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74731. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74732. }
  74733. var depCount = 0;
  74734. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74735. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74736. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74737. depCount++;
  74738. }
  74739. if (this.packedFloat) {
  74740. defines += "#define PACKEDFLOAT 1";
  74741. }
  74742. this.blockCompilation = false;
  74743. _super.prototype.updateEffect.call(this, defines, null, null, {
  74744. varyingCount: varyingCount,
  74745. depCount: depCount
  74746. }, onCompiled, onError);
  74747. };
  74748. /**
  74749. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74750. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74751. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74752. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74753. * The gaps between physical kernels are compensated for in the weighting of the samples
  74754. * @param idealKernel Ideal blur kernel.
  74755. * @return Nearest best kernel.
  74756. */
  74757. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74758. var v = Math.round(idealKernel);
  74759. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74760. var k = _a[_i];
  74761. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74762. return Math.max(k, 3);
  74763. }
  74764. }
  74765. return Math.max(v, 3);
  74766. };
  74767. /**
  74768. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74769. * @param x The point on the Gaussian distribution to sample.
  74770. * @return the value of the Gaussian function at x.
  74771. */
  74772. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74773. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74774. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74775. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74776. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74777. // truncated at around 1.3% of peak strength.
  74778. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74779. var sigma = (1 / 3);
  74780. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74781. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74782. var weight = (1.0 / denominator) * Math.exp(exponent);
  74783. return weight;
  74784. };
  74785. /**
  74786. * Generates a string that can be used as a floating point number in GLSL.
  74787. * @param x Value to print.
  74788. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74789. * @return GLSL float string.
  74790. */
  74791. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74792. if (decimalFigures === void 0) { decimalFigures = 8; }
  74793. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74794. };
  74795. return BlurPostProcess;
  74796. }(BABYLON.PostProcess));
  74797. BABYLON.BlurPostProcess = BlurPostProcess;
  74798. })(BABYLON || (BABYLON = {}));
  74799. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74800. var BABYLON;
  74801. (function (BABYLON) {
  74802. /**
  74803. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74804. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74805. * based on samples that have a large difference in distance than the center pixel.
  74806. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74807. */
  74808. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74809. __extends(DepthOfFieldBlurPostProcess, _super);
  74810. /**
  74811. * Creates a new instance CircleOfConfusionPostProcess
  74812. * @param name The name of the effect.
  74813. * @param scene The scene the effect belongs to.
  74814. * @param direction The direction the blur should be applied.
  74815. * @param kernel The size of the kernel used to blur.
  74816. * @param options The required width/height ratio to downsize to before computing the render pass.
  74817. * @param camera The camera to apply the render pass to.
  74818. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74819. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74820. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74821. * @param engine The engine which the post process will be applied. (default: current engine)
  74822. * @param reusable If the post process can be reused on the same frame. (default: false)
  74823. * @param textureType Type of textures used when performing the post process. (default: 0)
  74824. * @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)
  74825. */
  74826. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74827. if (imageToBlur === void 0) { imageToBlur = null; }
  74828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74829. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74830. if (blockCompilation === void 0) { blockCompilation = false; }
  74831. 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;
  74832. _this.direction = direction;
  74833. _this.onApplyObservable.add(function (effect) {
  74834. if (imageToBlur != null) {
  74835. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74836. }
  74837. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74838. if (scene.activeCamera) {
  74839. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74840. }
  74841. });
  74842. return _this;
  74843. }
  74844. return DepthOfFieldBlurPostProcess;
  74845. }(BABYLON.BlurPostProcess));
  74846. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74847. })(BABYLON || (BABYLON = {}));
  74848. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74849. var BABYLON;
  74850. (function (BABYLON) {
  74851. /**
  74852. * Options to be set when merging outputs from the default pipeline.
  74853. */
  74854. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74855. function DepthOfFieldMergePostProcessOptions() {
  74856. }
  74857. return DepthOfFieldMergePostProcessOptions;
  74858. }());
  74859. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74860. /**
  74861. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74862. */
  74863. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74864. __extends(DepthOfFieldMergePostProcess, _super);
  74865. /**
  74866. * Creates a new instance of DepthOfFieldMergePostProcess
  74867. * @param name The name of the effect.
  74868. * @param originalFromInput Post process which's input will be used for the merge.
  74869. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74870. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74871. * @param options The required width/height ratio to downsize to before computing the render pass.
  74872. * @param camera The camera to apply the render pass to.
  74873. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74874. * @param engine The engine which the post process will be applied. (default: current engine)
  74875. * @param reusable If the post process can be reused on the same frame. (default: false)
  74876. * @param textureType Type of textures used when performing the post process. (default: 0)
  74877. * @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)
  74878. */
  74879. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74880. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74881. if (blockCompilation === void 0) { blockCompilation = false; }
  74882. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74883. _this.blurSteps = blurSteps;
  74884. _this.onApplyObservable.add(function (effect) {
  74885. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74886. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74887. blurSteps.forEach(function (step, index) {
  74888. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74889. });
  74890. });
  74891. if (!blockCompilation) {
  74892. _this.updateEffect();
  74893. }
  74894. return _this;
  74895. }
  74896. /**
  74897. * Updates the effect with the current post process compile time values and recompiles the shader.
  74898. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74899. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74900. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74901. * @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
  74902. * @param onCompiled Called when the shader has been compiled.
  74903. * @param onError Called if there is an error when compiling a shader.
  74904. */
  74905. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74906. if (defines === void 0) { defines = null; }
  74907. if (uniforms === void 0) { uniforms = null; }
  74908. if (samplers === void 0) { samplers = null; }
  74909. if (!defines) {
  74910. defines = "";
  74911. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74912. }
  74913. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74914. };
  74915. return DepthOfFieldMergePostProcess;
  74916. }(BABYLON.PostProcess));
  74917. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74918. })(BABYLON || (BABYLON = {}));
  74919. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74920. var BABYLON;
  74921. (function (BABYLON) {
  74922. /**
  74923. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74924. */
  74925. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74926. __extends(CircleOfConfusionPostProcess, _super);
  74927. /**
  74928. * Creates a new instance CircleOfConfusionPostProcess
  74929. * @param name The name of the effect.
  74930. * @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.
  74931. * @param options The required width/height ratio to downsize to before computing the render pass.
  74932. * @param camera The camera to apply the render pass to.
  74933. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74934. * @param engine The engine which the post process will be applied. (default: current engine)
  74935. * @param reusable If the post process can be reused on the same frame. (default: false)
  74936. * @param textureType Type of textures used when performing the post process. (default: 0)
  74937. * @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)
  74938. */
  74939. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74940. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74941. if (blockCompilation === void 0) { blockCompilation = false; }
  74942. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74943. /**
  74944. * 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.
  74945. */
  74946. _this.lensSize = 50;
  74947. /**
  74948. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74949. */
  74950. _this.fStop = 1.4;
  74951. /**
  74952. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74953. */
  74954. _this.focusDistance = 2000;
  74955. /**
  74956. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74957. */
  74958. _this.focalLength = 50;
  74959. _this._depthTexture = null;
  74960. _this._depthTexture = depthTexture;
  74961. _this.onApplyObservable.add(function (effect) {
  74962. if (!_this._depthTexture) {
  74963. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74964. return;
  74965. }
  74966. effect.setTexture("depthSampler", _this._depthTexture);
  74967. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74968. var aperture = _this.lensSize / _this.fStop;
  74969. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74970. effect.setFloat('focusDistance', _this.focusDistance);
  74971. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74972. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74973. });
  74974. return _this;
  74975. }
  74976. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74977. /**
  74978. * 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.
  74979. */
  74980. set: function (value) {
  74981. this._depthTexture = value;
  74982. },
  74983. enumerable: true,
  74984. configurable: true
  74985. });
  74986. return CircleOfConfusionPostProcess;
  74987. }(BABYLON.PostProcess));
  74988. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74989. })(BABYLON || (BABYLON = {}));
  74990. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74991. var BABYLON;
  74992. (function (BABYLON) {
  74993. /**
  74994. * Specifies the level of max blur that should be applied when using the depth of field effect
  74995. */
  74996. var DepthOfFieldEffectBlurLevel;
  74997. (function (DepthOfFieldEffectBlurLevel) {
  74998. /**
  74999. * Subtle blur
  75000. */
  75001. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75002. /**
  75003. * Medium blur
  75004. */
  75005. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75006. /**
  75007. * Large blur
  75008. */
  75009. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75010. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75011. ;
  75012. /**
  75013. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75014. */
  75015. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75016. __extends(DepthOfFieldEffect, _super);
  75017. /**
  75018. * Creates a new instance DepthOfFieldEffect
  75019. * @param scene The scene the effect belongs to.
  75020. * @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.
  75021. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75022. * @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)
  75023. */
  75024. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75025. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75026. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75027. if (blockCompilation === void 0) { blockCompilation = false; }
  75028. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75029. return _this._effects;
  75030. }, true) || this;
  75031. /**
  75032. * Internal post processes in depth of field effect
  75033. */
  75034. _this._effects = [];
  75035. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75036. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75037. // 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)
  75038. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75039. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75040. _this._depthOfFieldBlurY = [];
  75041. _this._depthOfFieldBlurX = [];
  75042. var blurCount = 1;
  75043. var kernelSize = 15;
  75044. switch (blurLevel) {
  75045. case DepthOfFieldEffectBlurLevel.High: {
  75046. blurCount = 3;
  75047. kernelSize = 51;
  75048. break;
  75049. }
  75050. case DepthOfFieldEffectBlurLevel.Medium: {
  75051. blurCount = 2;
  75052. kernelSize = 31;
  75053. break;
  75054. }
  75055. default: {
  75056. kernelSize = 15;
  75057. blurCount = 1;
  75058. break;
  75059. }
  75060. }
  75061. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75062. var ratio = 1.0;
  75063. for (var i = 0; i < blurCount; i++) {
  75064. 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);
  75065. blurY.autoClear = false;
  75066. ratio = 0.75 / Math.pow(2, i);
  75067. 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);
  75068. blurX.autoClear = false;
  75069. _this._depthOfFieldBlurY.push(blurY);
  75070. _this._depthOfFieldBlurX.push(blurX);
  75071. }
  75072. // Set all post processes on the effect.
  75073. _this._effects = [_this._circleOfConfusion];
  75074. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75075. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75076. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75077. }
  75078. // Merge blurred images with original image based on circleOfConfusion
  75079. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75080. _this._dofMerge.autoClear = false;
  75081. _this._effects.push(_this._dofMerge);
  75082. return _this;
  75083. }
  75084. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75085. get: function () {
  75086. return this._circleOfConfusion.focalLength;
  75087. },
  75088. /**
  75089. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75090. */
  75091. set: function (value) {
  75092. this._circleOfConfusion.focalLength = value;
  75093. },
  75094. enumerable: true,
  75095. configurable: true
  75096. });
  75097. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75098. get: function () {
  75099. return this._circleOfConfusion.fStop;
  75100. },
  75101. /**
  75102. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75103. */
  75104. set: function (value) {
  75105. this._circleOfConfusion.fStop = value;
  75106. },
  75107. enumerable: true,
  75108. configurable: true
  75109. });
  75110. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75111. get: function () {
  75112. return this._circleOfConfusion.focusDistance;
  75113. },
  75114. /**
  75115. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75116. */
  75117. set: function (value) {
  75118. this._circleOfConfusion.focusDistance = value;
  75119. },
  75120. enumerable: true,
  75121. configurable: true
  75122. });
  75123. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75124. get: function () {
  75125. return this._circleOfConfusion.lensSize;
  75126. },
  75127. /**
  75128. * 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.
  75129. */
  75130. set: function (value) {
  75131. this._circleOfConfusion.lensSize = value;
  75132. },
  75133. enumerable: true,
  75134. configurable: true
  75135. });
  75136. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75137. /**
  75138. * 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.
  75139. */
  75140. set: function (value) {
  75141. this._circleOfConfusion.depthTexture = value;
  75142. },
  75143. enumerable: true,
  75144. configurable: true
  75145. });
  75146. /**
  75147. * Disposes each of the internal effects for a given camera.
  75148. * @param camera The camera to dispose the effect on.
  75149. */
  75150. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75151. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75152. this._effects[effectIndex].dispose(camera);
  75153. }
  75154. };
  75155. /**
  75156. * Internal
  75157. */
  75158. DepthOfFieldEffect.prototype._updateEffects = function () {
  75159. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75160. this._effects[effectIndex].updateEffect();
  75161. }
  75162. };
  75163. /**
  75164. * Internal
  75165. * @returns if all the contained post processes are ready.
  75166. */
  75167. DepthOfFieldEffect.prototype._isReady = function () {
  75168. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75169. if (!this._effects[effectIndex].isReady()) {
  75170. return false;
  75171. }
  75172. }
  75173. return true;
  75174. };
  75175. return DepthOfFieldEffect;
  75176. }(BABYLON.PostProcessRenderEffect));
  75177. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75178. })(BABYLON || (BABYLON = {}));
  75179. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75180. var BABYLON;
  75181. (function (BABYLON) {
  75182. /**
  75183. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75184. */
  75185. var BloomMergePostProcess = /** @class */ (function (_super) {
  75186. __extends(BloomMergePostProcess, _super);
  75187. /**
  75188. * Creates a new instance of @see BloomMergePostProcess
  75189. * @param name The name of the effect.
  75190. * @param originalFromInput Post process which's input will be used for the merge.
  75191. * @param blurred Blurred highlights post process which's output will be used.
  75192. * @param weight Weight of the bloom to be added to the original input.
  75193. * @param options The required width/height ratio to downsize to before computing the render pass.
  75194. * @param camera The camera to apply the render pass to.
  75195. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75196. * @param engine The engine which the post process will be applied. (default: current engine)
  75197. * @param reusable If the post process can be reused on the same frame. (default: false)
  75198. * @param textureType Type of textures used when performing the post process. (default: 0)
  75199. * @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)
  75200. */
  75201. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75202. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75203. if (blockCompilation === void 0) { blockCompilation = false; }
  75204. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75205. _this.weight = weight;
  75206. _this.onApplyObservable.add(function (effect) {
  75207. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75208. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75209. effect.setFloat("bloomWeight", _this.weight);
  75210. });
  75211. if (!blockCompilation) {
  75212. _this.updateEffect();
  75213. }
  75214. return _this;
  75215. }
  75216. return BloomMergePostProcess;
  75217. }(BABYLON.PostProcess));
  75218. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75219. })(BABYLON || (BABYLON = {}));
  75220. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75221. var BABYLON;
  75222. (function (BABYLON) {
  75223. /**
  75224. * 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.
  75225. */
  75226. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75227. __extends(ExtractHighlightsPostProcess, _super);
  75228. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75229. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75230. if (blockCompilation === void 0) { blockCompilation = false; }
  75231. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75232. /**
  75233. * The luminance threshold, pixels below this value will be set to black.
  75234. */
  75235. _this.threshold = 0.9;
  75236. /**
  75237. * Internal
  75238. */
  75239. _this._exposure = 1;
  75240. /**
  75241. * Post process which has the input texture to be used when performing highlight extraction
  75242. */
  75243. _this._inputPostProcess = null;
  75244. _this.onApplyObservable.add(function (effect) {
  75245. if (_this._inputPostProcess) {
  75246. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75247. }
  75248. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75249. effect.setFloat('exposure', _this._exposure);
  75250. });
  75251. return _this;
  75252. }
  75253. return ExtractHighlightsPostProcess;
  75254. }(BABYLON.PostProcess));
  75255. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75256. })(BABYLON || (BABYLON = {}));
  75257. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75258. var BABYLON;
  75259. (function (BABYLON) {
  75260. /**
  75261. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75262. */
  75263. var BloomEffect = /** @class */ (function (_super) {
  75264. __extends(BloomEffect, _super);
  75265. /**
  75266. * Creates a new instance of @see BloomEffect
  75267. * @param scene The scene the effect belongs to.
  75268. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75269. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75270. * @param bloomWeight The the strength of bloom.
  75271. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75272. * @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)
  75273. */
  75274. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75275. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75276. if (blockCompilation === void 0) { blockCompilation = false; }
  75277. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75278. return _this._effects;
  75279. }, true) || this;
  75280. _this.bloomScale = bloomScale;
  75281. /**
  75282. * Internal
  75283. */
  75284. _this._effects = [];
  75285. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75286. _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);
  75287. _this._blurX.alwaysForcePOT = true;
  75288. _this._blurX.autoClear = false;
  75289. _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);
  75290. _this._blurY.alwaysForcePOT = true;
  75291. _this._blurY.autoClear = false;
  75292. _this.kernel = bloomKernel;
  75293. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75294. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75295. _this._merge.autoClear = false;
  75296. _this._effects.push(_this._merge);
  75297. return _this;
  75298. }
  75299. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75300. /**
  75301. * The luminance threshold to find bright areas of the image to bloom.
  75302. */
  75303. get: function () {
  75304. return this._downscale.threshold;
  75305. },
  75306. set: function (value) {
  75307. this._downscale.threshold = value;
  75308. },
  75309. enumerable: true,
  75310. configurable: true
  75311. });
  75312. Object.defineProperty(BloomEffect.prototype, "weight", {
  75313. /**
  75314. * The strength of the bloom.
  75315. */
  75316. get: function () {
  75317. return this._merge.weight;
  75318. },
  75319. set: function (value) {
  75320. this._merge.weight = value;
  75321. },
  75322. enumerable: true,
  75323. configurable: true
  75324. });
  75325. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75326. /**
  75327. * Specifies the size of the bloom blur kernel, relative to the final output size
  75328. */
  75329. get: function () {
  75330. return this._blurX.kernel / this.bloomScale;
  75331. },
  75332. set: function (value) {
  75333. this._blurX.kernel = value * this.bloomScale;
  75334. this._blurY.kernel = value * this.bloomScale;
  75335. },
  75336. enumerable: true,
  75337. configurable: true
  75338. });
  75339. /**
  75340. * Disposes each of the internal effects for a given camera.
  75341. * @param camera The camera to dispose the effect on.
  75342. */
  75343. BloomEffect.prototype.disposeEffects = function (camera) {
  75344. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75345. this._effects[effectIndex].dispose(camera);
  75346. }
  75347. };
  75348. /**
  75349. * Internal
  75350. */
  75351. BloomEffect.prototype._updateEffects = function () {
  75352. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75353. this._effects[effectIndex].updateEffect();
  75354. }
  75355. };
  75356. /**
  75357. * Internal
  75358. * @returns if all the contained post processes are ready.
  75359. */
  75360. BloomEffect.prototype._isReady = function () {
  75361. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75362. if (!this._effects[effectIndex].isReady()) {
  75363. return false;
  75364. }
  75365. }
  75366. return true;
  75367. };
  75368. return BloomEffect;
  75369. }(BABYLON.PostProcessRenderEffect));
  75370. BABYLON.BloomEffect = BloomEffect;
  75371. })(BABYLON || (BABYLON = {}));
  75372. //# sourceMappingURL=babylon.bloomEffect.js.map
  75373. var BABYLON;
  75374. (function (BABYLON) {
  75375. /**
  75376. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75377. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75378. */
  75379. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75380. __extends(DefaultRenderingPipeline, _super);
  75381. /**
  75382. * @constructor
  75383. * @param {string} name - The rendering pipeline name
  75384. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75385. * @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)
  75386. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75387. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75388. */
  75389. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75390. if (automaticBuild === void 0) { automaticBuild = true; }
  75391. var _this = _super.call(this, scene.getEngine(), name) || this;
  75392. _this._originalCameras = [];
  75393. /**
  75394. * ID of the sharpen post process,
  75395. */
  75396. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75397. /**
  75398. * ID of the image processing post process;
  75399. */
  75400. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75401. /**
  75402. * ID of the Fast Approximate Anti-Aliasing post process;
  75403. */
  75404. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75405. /**
  75406. * ID of the chromatic aberration post process,
  75407. */
  75408. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75409. /**
  75410. * ID of the grain post process
  75411. */
  75412. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75413. /**
  75414. * Animations which can be used to tweak settings over a period of time
  75415. */
  75416. _this.animations = [];
  75417. _this._imageProcessingConfigurationObserver = null;
  75418. // Values
  75419. _this._sharpenEnabled = false;
  75420. _this._bloomEnabled = false;
  75421. _this._depthOfFieldEnabled = false;
  75422. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75423. _this._fxaaEnabled = false;
  75424. _this._imageProcessingEnabled = true;
  75425. _this._bloomScale = 0.5;
  75426. _this._chromaticAberrationEnabled = false;
  75427. _this._grainEnabled = false;
  75428. _this._buildAllowed = true;
  75429. _this._resizeObserver = null;
  75430. _this._hardwareScaleLevel = 1.0;
  75431. _this._bloomKernel = 64;
  75432. /**
  75433. * Specifies the weight of the bloom in the final rendering
  75434. */
  75435. _this._bloomWeight = 0.15;
  75436. /**
  75437. * Specifies the luma threshold for the area that will be blurred by the bloom
  75438. */
  75439. _this._bloomThreshold = 0.9;
  75440. _this._samples = 1;
  75441. _this._hasCleared = false;
  75442. _this._prevPostProcess = null;
  75443. _this._prevPrevPostProcess = null;
  75444. _this._cameras = cameras || [];
  75445. _this._originalCameras = _this._cameras.slice();
  75446. _this._buildAllowed = automaticBuild;
  75447. // Initialize
  75448. _this._scene = scene;
  75449. var caps = _this._scene.getEngine().getCaps();
  75450. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75451. // Misc
  75452. if (_this._hdr) {
  75453. if (caps.textureHalfFloatRender) {
  75454. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75455. }
  75456. else if (caps.textureFloatRender) {
  75457. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75458. }
  75459. }
  75460. else {
  75461. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75462. }
  75463. // Attach
  75464. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75465. var engine = _this._scene.getEngine();
  75466. // Create post processes before hand so they can be modified before enabled.
  75467. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75468. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75469. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75470. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75471. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75472. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75473. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75474. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75475. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75476. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75477. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75478. _this.bloomKernel = _this.bloomKernel;
  75479. });
  75480. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75481. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75482. });
  75483. _this._buildPipeline();
  75484. return _this;
  75485. }
  75486. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75487. get: function () {
  75488. return this._sharpenEnabled;
  75489. },
  75490. /**
  75491. * Enable or disable the sharpen process from the pipeline
  75492. */
  75493. set: function (enabled) {
  75494. if (this._sharpenEnabled === enabled) {
  75495. return;
  75496. }
  75497. this._sharpenEnabled = enabled;
  75498. this._buildPipeline();
  75499. },
  75500. enumerable: true,
  75501. configurable: true
  75502. });
  75503. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75504. /**
  75505. * Specifies the size of the bloom blur kernel, relative to the final output size
  75506. */
  75507. get: function () {
  75508. return this._bloomKernel;
  75509. },
  75510. set: function (value) {
  75511. this._bloomKernel = value;
  75512. this.bloom.kernel = value / this._hardwareScaleLevel;
  75513. },
  75514. enumerable: true,
  75515. configurable: true
  75516. });
  75517. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75518. get: function () {
  75519. return this._bloomWeight;
  75520. },
  75521. /**
  75522. * The strength of the bloom.
  75523. */
  75524. set: function (value) {
  75525. if (this._bloomWeight === value) {
  75526. return;
  75527. }
  75528. this.bloom.weight = value;
  75529. this._bloomWeight = value;
  75530. },
  75531. enumerable: true,
  75532. configurable: true
  75533. });
  75534. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75535. get: function () {
  75536. return this._bloomThreshold;
  75537. },
  75538. /**
  75539. * The strength of the bloom.
  75540. */
  75541. set: function (value) {
  75542. if (this._bloomThreshold === value) {
  75543. return;
  75544. }
  75545. this.bloom.threshold = value;
  75546. this._bloomThreshold = value;
  75547. },
  75548. enumerable: true,
  75549. configurable: true
  75550. });
  75551. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75552. get: function () {
  75553. return this._bloomScale;
  75554. },
  75555. /**
  75556. * The scale of the bloom, lower value will provide better performance.
  75557. */
  75558. set: function (value) {
  75559. if (this._bloomScale === value) {
  75560. return;
  75561. }
  75562. this._bloomScale = value;
  75563. // recreate bloom and dispose old as this setting is not dynamic
  75564. this._rebuildBloom();
  75565. this._buildPipeline();
  75566. },
  75567. enumerable: true,
  75568. configurable: true
  75569. });
  75570. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75571. get: function () {
  75572. return this._bloomEnabled;
  75573. },
  75574. /**
  75575. * Enable or disable the bloom from the pipeline
  75576. */
  75577. set: function (enabled) {
  75578. if (this._bloomEnabled === enabled) {
  75579. return;
  75580. }
  75581. this._bloomEnabled = enabled;
  75582. this._buildPipeline();
  75583. },
  75584. enumerable: true,
  75585. configurable: true
  75586. });
  75587. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75588. // recreate bloom and dispose old as this setting is not dynamic
  75589. var oldBloom = this.bloom;
  75590. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75591. this.bloom.threshold = oldBloom.threshold;
  75592. for (var i = 0; i < this._cameras.length; i++) {
  75593. oldBloom.disposeEffects(this._cameras[i]);
  75594. }
  75595. };
  75596. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75597. /**
  75598. * If the depth of field is enabled.
  75599. */
  75600. get: function () {
  75601. return this._depthOfFieldEnabled;
  75602. },
  75603. set: function (enabled) {
  75604. if (this._depthOfFieldEnabled === enabled) {
  75605. return;
  75606. }
  75607. this._depthOfFieldEnabled = enabled;
  75608. this._buildPipeline();
  75609. },
  75610. enumerable: true,
  75611. configurable: true
  75612. });
  75613. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75614. /**
  75615. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75616. */
  75617. get: function () {
  75618. return this._depthOfFieldBlurLevel;
  75619. },
  75620. set: function (value) {
  75621. if (this._depthOfFieldBlurLevel === value) {
  75622. return;
  75623. }
  75624. this._depthOfFieldBlurLevel = value;
  75625. // recreate dof and dispose old as this setting is not dynamic
  75626. var oldDof = this.depthOfField;
  75627. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75628. this.depthOfField.focalLength = oldDof.focalLength;
  75629. this.depthOfField.focusDistance = oldDof.focusDistance;
  75630. this.depthOfField.fStop = oldDof.fStop;
  75631. this.depthOfField.lensSize = oldDof.lensSize;
  75632. for (var i = 0; i < this._cameras.length; i++) {
  75633. oldDof.disposeEffects(this._cameras[i]);
  75634. }
  75635. this._buildPipeline();
  75636. },
  75637. enumerable: true,
  75638. configurable: true
  75639. });
  75640. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75641. get: function () {
  75642. return this._fxaaEnabled;
  75643. },
  75644. /**
  75645. * If the anti aliasing is enabled.
  75646. */
  75647. set: function (enabled) {
  75648. if (this._fxaaEnabled === enabled) {
  75649. return;
  75650. }
  75651. this._fxaaEnabled = enabled;
  75652. this._buildPipeline();
  75653. },
  75654. enumerable: true,
  75655. configurable: true
  75656. });
  75657. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75658. get: function () {
  75659. return this._samples;
  75660. },
  75661. /**
  75662. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75663. */
  75664. set: function (sampleCount) {
  75665. if (this._samples === sampleCount) {
  75666. return;
  75667. }
  75668. this._samples = sampleCount;
  75669. this._buildPipeline();
  75670. },
  75671. enumerable: true,
  75672. configurable: true
  75673. });
  75674. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75675. get: function () {
  75676. return this._imageProcessingEnabled;
  75677. },
  75678. /**
  75679. * If image processing is enabled.
  75680. */
  75681. set: function (enabled) {
  75682. if (this._imageProcessingEnabled === enabled) {
  75683. return;
  75684. }
  75685. this._imageProcessingEnabled = enabled;
  75686. this._buildPipeline();
  75687. },
  75688. enumerable: true,
  75689. configurable: true
  75690. });
  75691. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75692. get: function () {
  75693. return this._chromaticAberrationEnabled;
  75694. },
  75695. /**
  75696. * Enable or disable the chromaticAberration process from the pipeline
  75697. */
  75698. set: function (enabled) {
  75699. if (this._chromaticAberrationEnabled === enabled) {
  75700. return;
  75701. }
  75702. this._chromaticAberrationEnabled = enabled;
  75703. this._buildPipeline();
  75704. },
  75705. enumerable: true,
  75706. configurable: true
  75707. });
  75708. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75709. get: function () {
  75710. return this._grainEnabled;
  75711. },
  75712. /**
  75713. * Enable or disable the grain process from the pipeline
  75714. */
  75715. set: function (enabled) {
  75716. if (this._grainEnabled === enabled) {
  75717. return;
  75718. }
  75719. this._grainEnabled = enabled;
  75720. this._buildPipeline();
  75721. },
  75722. enumerable: true,
  75723. configurable: true
  75724. });
  75725. /**
  75726. * Force the compilation of the entire pipeline.
  75727. */
  75728. DefaultRenderingPipeline.prototype.prepare = function () {
  75729. var previousState = this._buildAllowed;
  75730. this._buildAllowed = true;
  75731. this._buildPipeline();
  75732. this._buildAllowed = previousState;
  75733. };
  75734. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75735. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75736. if (this._hasCleared) {
  75737. postProcess.autoClear = false;
  75738. }
  75739. else {
  75740. postProcess.autoClear = true;
  75741. this._scene.autoClear = false;
  75742. this._hasCleared = true;
  75743. }
  75744. if (!skipTextureSharing) {
  75745. if (this._prevPrevPostProcess) {
  75746. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75747. }
  75748. else {
  75749. postProcess.useOwnOutput();
  75750. }
  75751. if (this._prevPostProcess) {
  75752. this._prevPrevPostProcess = this._prevPostProcess;
  75753. }
  75754. this._prevPostProcess = postProcess;
  75755. }
  75756. };
  75757. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75758. var _this = this;
  75759. if (!this._buildAllowed) {
  75760. return;
  75761. }
  75762. this._scene.autoClear = true;
  75763. var engine = this._scene.getEngine();
  75764. this._disposePostProcesses();
  75765. if (this._cameras !== null) {
  75766. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75767. // get back cameras to be used to reattach pipeline
  75768. this._cameras = this._originalCameras.slice();
  75769. }
  75770. this._reset();
  75771. this._prevPostProcess = null;
  75772. this._prevPrevPostProcess = null;
  75773. this._hasCleared = false;
  75774. if (this.depthOfFieldEnabled) {
  75775. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75776. this.depthOfField.depthTexture = depthTexture;
  75777. if (!this.depthOfField._isReady()) {
  75778. this.depthOfField._updateEffects();
  75779. }
  75780. this.addEffect(this.depthOfField);
  75781. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75782. }
  75783. if (this.bloomEnabled) {
  75784. if (!this.bloom._isReady()) {
  75785. this.bloom._updateEffects();
  75786. }
  75787. this.addEffect(this.bloom);
  75788. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75789. }
  75790. if (this._imageProcessingEnabled) {
  75791. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75792. if (this._hdr) {
  75793. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75794. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75795. }
  75796. else {
  75797. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75798. }
  75799. }
  75800. if (this.sharpenEnabled) {
  75801. if (!this.sharpen.isReady()) {
  75802. this.sharpen.updateEffect();
  75803. }
  75804. this.addEffect(this._sharpenEffect);
  75805. this._setAutoClearAndTextureSharing(this.sharpen);
  75806. }
  75807. if (this.grainEnabled) {
  75808. if (!this.grain.isReady()) {
  75809. this.grain.updateEffect();
  75810. }
  75811. this.addEffect(this._grainEffect);
  75812. this._setAutoClearAndTextureSharing(this.grain);
  75813. }
  75814. if (this.chromaticAberrationEnabled) {
  75815. if (!this.chromaticAberration.isReady()) {
  75816. this.chromaticAberration.updateEffect();
  75817. }
  75818. this.addEffect(this._chromaticAberrationEffect);
  75819. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75820. }
  75821. if (this.fxaaEnabled) {
  75822. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75823. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75824. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75825. }
  75826. if (this._cameras !== null) {
  75827. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75828. }
  75829. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75830. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75831. }
  75832. };
  75833. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75834. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75835. for (var i = 0; i < this._cameras.length; i++) {
  75836. var camera = this._cameras[i];
  75837. if (this.imageProcessing) {
  75838. this.imageProcessing.dispose(camera);
  75839. }
  75840. if (this.fxaa) {
  75841. this.fxaa.dispose(camera);
  75842. }
  75843. // These are created in the constructor and should not be disposed on every pipeline change
  75844. if (disposeNonRecreated) {
  75845. if (this.sharpen) {
  75846. this.sharpen.dispose(camera);
  75847. }
  75848. if (this.depthOfField) {
  75849. this.depthOfField.disposeEffects(camera);
  75850. }
  75851. if (this.bloom) {
  75852. this.bloom.disposeEffects(camera);
  75853. }
  75854. if (this.chromaticAberration) {
  75855. this.chromaticAberration.dispose(camera);
  75856. }
  75857. if (this.grain) {
  75858. this.grain.dispose(camera);
  75859. }
  75860. }
  75861. }
  75862. this.imageProcessing = null;
  75863. this.fxaa = null;
  75864. if (disposeNonRecreated) {
  75865. this.sharpen = null;
  75866. this._sharpenEffect = null;
  75867. this.depthOfField = null;
  75868. this.bloom = null;
  75869. this.chromaticAberration = null;
  75870. this._chromaticAberrationEffect = null;
  75871. this.grain = null;
  75872. this._grainEffect = null;
  75873. }
  75874. };
  75875. /**
  75876. * Dispose of the pipeline and stop all post processes
  75877. */
  75878. DefaultRenderingPipeline.prototype.dispose = function () {
  75879. this._disposePostProcesses(true);
  75880. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75881. this._scene.autoClear = true;
  75882. if (this._resizeObserver) {
  75883. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75884. this._resizeObserver = null;
  75885. }
  75886. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75887. _super.prototype.dispose.call(this);
  75888. };
  75889. /**
  75890. * Serialize the rendering pipeline (Used when exporting)
  75891. * @returns the serialized object
  75892. */
  75893. DefaultRenderingPipeline.prototype.serialize = function () {
  75894. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75895. serializationObject.customType = "DefaultRenderingPipeline";
  75896. return serializationObject;
  75897. };
  75898. /**
  75899. * Parse the serialized pipeline
  75900. * @param source Source pipeline.
  75901. * @param scene The scene to load the pipeline to.
  75902. * @param rootUrl The URL of the serialized pipeline.
  75903. * @returns An instantiated pipeline from the serialized object.
  75904. */
  75905. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75906. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75907. };
  75908. __decorate([
  75909. BABYLON.serialize()
  75910. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75911. __decorate([
  75912. BABYLON.serialize()
  75913. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75914. __decorate([
  75915. BABYLON.serialize()
  75916. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75917. __decorate([
  75918. BABYLON.serialize()
  75919. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75920. __decorate([
  75921. BABYLON.serialize()
  75922. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75923. __decorate([
  75924. BABYLON.serialize()
  75925. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75926. __decorate([
  75927. BABYLON.serialize()
  75928. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75929. __decorate([
  75930. BABYLON.serialize()
  75931. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75932. __decorate([
  75933. BABYLON.serialize()
  75934. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75935. __decorate([
  75936. BABYLON.serialize()
  75937. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75938. __decorate([
  75939. BABYLON.serialize()
  75940. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75941. __decorate([
  75942. BABYLON.serialize()
  75943. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75944. __decorate([
  75945. BABYLON.serialize()
  75946. ], DefaultRenderingPipeline.prototype, "samples", null);
  75947. __decorate([
  75948. BABYLON.serialize()
  75949. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75950. __decorate([
  75951. BABYLON.serialize()
  75952. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75953. __decorate([
  75954. BABYLON.serialize()
  75955. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75956. return DefaultRenderingPipeline;
  75957. }(BABYLON.PostProcessRenderPipeline));
  75958. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75959. })(BABYLON || (BABYLON = {}));
  75960. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75961. var BABYLON;
  75962. (function (BABYLON) {
  75963. /**
  75964. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75965. */
  75966. var GeometryBufferRenderer = /** @class */ (function () {
  75967. /**
  75968. * Creates a new G Buffer for the scene
  75969. * @param scene The scene the buffer belongs to
  75970. * @param ratio How big is the buffer related to the main canvas.
  75971. */
  75972. function GeometryBufferRenderer(scene, ratio) {
  75973. if (ratio === void 0) { ratio = 1; }
  75974. this._enablePosition = false;
  75975. this._scene = scene;
  75976. this._ratio = ratio;
  75977. // Render target
  75978. this._createRenderTargets();
  75979. }
  75980. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75981. /**
  75982. * Set the render list (meshes to be rendered) used in the G buffer.
  75983. */
  75984. set: function (meshes) {
  75985. this._multiRenderTarget.renderList = meshes;
  75986. },
  75987. enumerable: true,
  75988. configurable: true
  75989. });
  75990. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75991. /**
  75992. * Gets wether or not G buffer are supported by the running hardware.
  75993. * This requires draw buffer supports
  75994. */
  75995. get: function () {
  75996. return this._multiRenderTarget.isSupported;
  75997. },
  75998. enumerable: true,
  75999. configurable: true
  76000. });
  76001. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76002. /**
  76003. * Gets wether or not position are enabled for the G buffer.
  76004. */
  76005. get: function () {
  76006. return this._enablePosition;
  76007. },
  76008. /**
  76009. * Sets wether or not position are enabled for the G buffer.
  76010. */
  76011. set: function (enable) {
  76012. this._enablePosition = enable;
  76013. this.dispose();
  76014. this._createRenderTargets();
  76015. },
  76016. enumerable: true,
  76017. configurable: true
  76018. });
  76019. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76020. /**
  76021. * Gets the scene associated with the buffer.
  76022. */
  76023. get: function () {
  76024. return this._scene;
  76025. },
  76026. enumerable: true,
  76027. configurable: true
  76028. });
  76029. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76030. /**
  76031. * Gets the ratio used by the buffer during its creation.
  76032. * How big is the buffer related to the main canvas.
  76033. */
  76034. get: function () {
  76035. return this._ratio;
  76036. },
  76037. enumerable: true,
  76038. configurable: true
  76039. });
  76040. /**
  76041. * Checks wether everything is ready to render a submesh to the G buffer.
  76042. * @param subMesh the submesh to check readiness for
  76043. * @param useInstances is the mesh drawn using instance or not
  76044. * @returns true if ready otherwise false
  76045. */
  76046. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76047. var material = subMesh.getMaterial();
  76048. if (material && material.disableDepthWrite) {
  76049. return false;
  76050. }
  76051. var defines = [];
  76052. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76053. var mesh = subMesh.getMesh();
  76054. // Alpha test
  76055. if (material && material.needAlphaTesting()) {
  76056. defines.push("#define ALPHATEST");
  76057. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76058. attribs.push(BABYLON.VertexBuffer.UVKind);
  76059. defines.push("#define UV1");
  76060. }
  76061. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76062. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76063. defines.push("#define UV2");
  76064. }
  76065. }
  76066. // Buffers
  76067. if (this._enablePosition) {
  76068. defines.push("#define POSITION");
  76069. }
  76070. // Bones
  76071. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76072. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76073. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76074. if (mesh.numBoneInfluencers > 4) {
  76075. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76076. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76077. }
  76078. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76079. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76080. }
  76081. else {
  76082. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76083. }
  76084. // Instances
  76085. if (useInstances) {
  76086. defines.push("#define INSTANCES");
  76087. attribs.push("world0");
  76088. attribs.push("world1");
  76089. attribs.push("world2");
  76090. attribs.push("world3");
  76091. }
  76092. // Get correct effect
  76093. var join = defines.join("\n");
  76094. if (this._cachedDefines !== join) {
  76095. this._cachedDefines = join;
  76096. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76097. }
  76098. return this._effect.isReady();
  76099. };
  76100. /**
  76101. * Gets the current underlying G Buffer.
  76102. * @returns the buffer
  76103. */
  76104. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76105. return this._multiRenderTarget;
  76106. };
  76107. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76108. /**
  76109. * Gets the number of samples used to render the buffer (anti aliasing).
  76110. */
  76111. get: function () {
  76112. return this._multiRenderTarget.samples;
  76113. },
  76114. /**
  76115. * Sets the number of samples used to render the buffer (anti aliasing).
  76116. */
  76117. set: function (value) {
  76118. this._multiRenderTarget.samples = value;
  76119. },
  76120. enumerable: true,
  76121. configurable: true
  76122. });
  76123. /**
  76124. * Disposes the renderer and frees up associated resources.
  76125. */
  76126. GeometryBufferRenderer.prototype.dispose = function () {
  76127. this.getGBuffer().dispose();
  76128. };
  76129. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76130. var _this = this;
  76131. var engine = this._scene.getEngine();
  76132. var count = this._enablePosition ? 3 : 2;
  76133. 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 });
  76134. if (!this.isSupported) {
  76135. return;
  76136. }
  76137. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76138. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76139. this._multiRenderTarget.refreshRate = 1;
  76140. this._multiRenderTarget.renderParticles = false;
  76141. this._multiRenderTarget.renderList = null;
  76142. // set default depth value to 1.0 (far away)
  76143. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76144. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76145. });
  76146. // Custom render function
  76147. var renderSubMesh = function (subMesh) {
  76148. var mesh = subMesh.getRenderingMesh();
  76149. var scene = _this._scene;
  76150. var engine = scene.getEngine();
  76151. var material = subMesh.getMaterial();
  76152. if (!material) {
  76153. return;
  76154. }
  76155. // Culling
  76156. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76157. // Managing instances
  76158. var batch = mesh._getInstancesRenderList(subMesh._id);
  76159. if (batch.mustReturn) {
  76160. return;
  76161. }
  76162. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76163. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76164. engine.enableEffect(_this._effect);
  76165. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76166. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76167. _this._effect.setMatrix("view", scene.getViewMatrix());
  76168. // Alpha test
  76169. if (material && material.needAlphaTesting()) {
  76170. var alphaTexture = material.getAlphaTestTexture();
  76171. if (alphaTexture) {
  76172. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76173. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76174. }
  76175. }
  76176. // Bones
  76177. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76178. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76179. }
  76180. // Draw
  76181. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76182. }
  76183. };
  76184. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76185. var index;
  76186. if (depthOnlySubMeshes.length) {
  76187. engine.setColorWrite(false);
  76188. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76189. renderSubMesh(depthOnlySubMeshes.data[index]);
  76190. }
  76191. engine.setColorWrite(true);
  76192. }
  76193. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76194. renderSubMesh(opaqueSubMeshes.data[index]);
  76195. }
  76196. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76197. renderSubMesh(alphaTestSubMeshes.data[index]);
  76198. }
  76199. };
  76200. };
  76201. return GeometryBufferRenderer;
  76202. }());
  76203. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76204. })(BABYLON || (BABYLON = {}));
  76205. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76206. var BABYLON;
  76207. (function (BABYLON) {
  76208. var RefractionPostProcess = /** @class */ (function (_super) {
  76209. __extends(RefractionPostProcess, _super);
  76210. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76211. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76212. _this.color = color;
  76213. _this.depth = depth;
  76214. _this.colorLevel = colorLevel;
  76215. _this._ownRefractionTexture = true;
  76216. _this.onActivateObservable.add(function (cam) {
  76217. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76218. });
  76219. _this.onApplyObservable.add(function (effect) {
  76220. effect.setColor3("baseColor", _this.color);
  76221. effect.setFloat("depth", _this.depth);
  76222. effect.setFloat("colorLevel", _this.colorLevel);
  76223. effect.setTexture("refractionSampler", _this._refTexture);
  76224. });
  76225. return _this;
  76226. }
  76227. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76228. /**
  76229. * Gets or sets the refraction texture
  76230. * Please note that you are responsible for disposing the texture if you set it manually
  76231. */
  76232. get: function () {
  76233. return this._refTexture;
  76234. },
  76235. set: function (value) {
  76236. if (this._refTexture && this._ownRefractionTexture) {
  76237. this._refTexture.dispose();
  76238. }
  76239. this._refTexture = value;
  76240. this._ownRefractionTexture = false;
  76241. },
  76242. enumerable: true,
  76243. configurable: true
  76244. });
  76245. // Methods
  76246. RefractionPostProcess.prototype.dispose = function (camera) {
  76247. if (this._refTexture && this._ownRefractionTexture) {
  76248. this._refTexture.dispose();
  76249. this._refTexture = null;
  76250. }
  76251. _super.prototype.dispose.call(this, camera);
  76252. };
  76253. return RefractionPostProcess;
  76254. }(BABYLON.PostProcess));
  76255. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76256. })(BABYLON || (BABYLON = {}));
  76257. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76258. var BABYLON;
  76259. (function (BABYLON) {
  76260. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76261. __extends(BlackAndWhitePostProcess, _super);
  76262. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76263. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76264. _this.degree = 1;
  76265. _this.onApplyObservable.add(function (effect) {
  76266. effect.setFloat("degree", _this.degree);
  76267. });
  76268. return _this;
  76269. }
  76270. return BlackAndWhitePostProcess;
  76271. }(BABYLON.PostProcess));
  76272. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76273. })(BABYLON || (BABYLON = {}));
  76274. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76275. var BABYLON;
  76276. (function (BABYLON) {
  76277. /**
  76278. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76279. * input texture to perform effects such as edge detection or sharpening
  76280. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76281. */
  76282. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76283. __extends(ConvolutionPostProcess, _super);
  76284. /**
  76285. * Creates a new instance ConvolutionPostProcess
  76286. * @param name The name of the effect.
  76287. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76288. * @param options The required width/height ratio to downsize to before computing the render pass.
  76289. * @param camera The camera to apply the render pass to.
  76290. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76291. * @param engine The engine which the post process will be applied. (default: current engine)
  76292. * @param reusable If the post process can be reused on the same frame. (default: false)
  76293. * @param textureType Type of textures used when performing the post process. (default: 0)
  76294. */
  76295. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76296. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76297. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76298. _this.kernel = kernel;
  76299. _this.onApply = function (effect) {
  76300. effect.setFloat2("screenSize", _this.width, _this.height);
  76301. effect.setArray("kernel", _this.kernel);
  76302. };
  76303. return _this;
  76304. }
  76305. // Statics
  76306. /**
  76307. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76308. */
  76309. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76310. /**
  76311. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76312. */
  76313. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76314. /**
  76315. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76316. */
  76317. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76318. /**
  76319. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76320. */
  76321. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76322. /**
  76323. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76324. */
  76325. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76326. /**
  76327. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76328. */
  76329. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76330. return ConvolutionPostProcess;
  76331. }(BABYLON.PostProcess));
  76332. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76333. })(BABYLON || (BABYLON = {}));
  76334. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76335. var BABYLON;
  76336. (function (BABYLON) {
  76337. var FilterPostProcess = /** @class */ (function (_super) {
  76338. __extends(FilterPostProcess, _super);
  76339. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76340. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76341. _this.kernelMatrix = kernelMatrix;
  76342. _this.onApply = function (effect) {
  76343. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76344. };
  76345. return _this;
  76346. }
  76347. return FilterPostProcess;
  76348. }(BABYLON.PostProcess));
  76349. BABYLON.FilterPostProcess = FilterPostProcess;
  76350. })(BABYLON || (BABYLON = {}));
  76351. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76352. var BABYLON;
  76353. (function (BABYLON) {
  76354. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76355. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76356. __extends(VolumetricLightScatteringPostProcess, _super);
  76357. /**
  76358. * @constructor
  76359. * @param {string} name - The post-process name
  76360. * @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)
  76361. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76362. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76363. * @param {number} samples - The post-process quality, default 100
  76364. * @param {number} samplingMode - The post-process filtering mode
  76365. * @param {BABYLON.Engine} engine - The babylon engine
  76366. * @param {boolean} reusable - If the post-process is reusable
  76367. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76368. */
  76369. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76370. if (samples === void 0) { samples = 100; }
  76371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76372. 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;
  76373. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76374. /**
  76375. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76376. */
  76377. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76378. /**
  76379. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76380. */
  76381. _this.useCustomMeshPosition = false;
  76382. /**
  76383. * If the post-process should inverse the light scattering direction
  76384. */
  76385. _this.invert = true;
  76386. /**
  76387. * Array containing the excluded meshes not rendered in the internal pass
  76388. */
  76389. _this.excludedMeshes = new Array();
  76390. /**
  76391. * Controls the overall intensity of the post-process
  76392. */
  76393. _this.exposure = 0.3;
  76394. /**
  76395. * Dissipates each sample's contribution in range [0, 1]
  76396. */
  76397. _this.decay = 0.96815;
  76398. /**
  76399. * Controls the overall intensity of each sample
  76400. */
  76401. _this.weight = 0.58767;
  76402. /**
  76403. * Controls the density of each sample
  76404. */
  76405. _this.density = 0.926;
  76406. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76407. engine = scene.getEngine();
  76408. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76409. // Configure mesh
  76410. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76411. // Configure
  76412. _this._createPass(scene, ratio.passRatio || ratio);
  76413. _this.onActivate = function (camera) {
  76414. if (!_this.isSupported) {
  76415. _this.dispose(camera);
  76416. }
  76417. _this.onActivate = null;
  76418. };
  76419. _this.onApplyObservable.add(function (effect) {
  76420. _this._updateMeshScreenCoordinates(scene);
  76421. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76422. effect.setFloat("exposure", _this.exposure);
  76423. effect.setFloat("decay", _this.decay);
  76424. effect.setFloat("weight", _this.weight);
  76425. effect.setFloat("density", _this.density);
  76426. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76427. });
  76428. return _this;
  76429. }
  76430. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76431. get: function () {
  76432. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76433. return false;
  76434. },
  76435. set: function (useDiffuseColor) {
  76436. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76437. },
  76438. enumerable: true,
  76439. configurable: true
  76440. });
  76441. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76442. return "VolumetricLightScatteringPostProcess";
  76443. };
  76444. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76445. var mesh = subMesh.getMesh();
  76446. // Render this.mesh as default
  76447. if (mesh === this.mesh && mesh.material) {
  76448. return mesh.material.isReady(mesh);
  76449. }
  76450. var defines = [];
  76451. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76452. var material = subMesh.getMaterial();
  76453. // Alpha test
  76454. if (material) {
  76455. if (material.needAlphaTesting()) {
  76456. defines.push("#define ALPHATEST");
  76457. }
  76458. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76459. attribs.push(BABYLON.VertexBuffer.UVKind);
  76460. defines.push("#define UV1");
  76461. }
  76462. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76463. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76464. defines.push("#define UV2");
  76465. }
  76466. }
  76467. // Bones
  76468. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76469. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76470. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76471. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76472. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76473. }
  76474. else {
  76475. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76476. }
  76477. // Instances
  76478. if (useInstances) {
  76479. defines.push("#define INSTANCES");
  76480. attribs.push("world0");
  76481. attribs.push("world1");
  76482. attribs.push("world2");
  76483. attribs.push("world3");
  76484. }
  76485. // Get correct effect
  76486. var join = defines.join("\n");
  76487. if (this._cachedDefines !== join) {
  76488. this._cachedDefines = join;
  76489. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76490. }
  76491. return this._volumetricLightScatteringPass.isReady();
  76492. };
  76493. /**
  76494. * Sets the new light position for light scattering effect
  76495. * @param {BABYLON.Vector3} The new custom light position
  76496. */
  76497. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76498. this.customMeshPosition = position;
  76499. };
  76500. /**
  76501. * Returns the light position for light scattering effect
  76502. * @return {BABYLON.Vector3} The custom light position
  76503. */
  76504. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76505. return this.customMeshPosition;
  76506. };
  76507. /**
  76508. * Disposes the internal assets and detaches the post-process from the camera
  76509. */
  76510. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76511. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76512. if (rttIndex !== -1) {
  76513. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76514. }
  76515. this._volumetricLightScatteringRTT.dispose();
  76516. _super.prototype.dispose.call(this, camera);
  76517. };
  76518. /**
  76519. * Returns the render target texture used by the post-process
  76520. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76521. */
  76522. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76523. return this._volumetricLightScatteringRTT;
  76524. };
  76525. // Private methods
  76526. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76527. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76528. return true;
  76529. }
  76530. return false;
  76531. };
  76532. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76533. var _this = this;
  76534. var engine = scene.getEngine();
  76535. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76536. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76537. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76538. this._volumetricLightScatteringRTT.renderList = null;
  76539. this._volumetricLightScatteringRTT.renderParticles = false;
  76540. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76541. var camera = this.getCamera();
  76542. if (camera) {
  76543. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76544. }
  76545. else {
  76546. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76547. }
  76548. // Custom render function for submeshes
  76549. var renderSubMesh = function (subMesh) {
  76550. var mesh = subMesh.getRenderingMesh();
  76551. if (_this._meshExcluded(mesh)) {
  76552. return;
  76553. }
  76554. var material = subMesh.getMaterial();
  76555. if (!material) {
  76556. return;
  76557. }
  76558. var scene = mesh.getScene();
  76559. var engine = scene.getEngine();
  76560. // Culling
  76561. engine.setState(material.backFaceCulling);
  76562. // Managing instances
  76563. var batch = mesh._getInstancesRenderList(subMesh._id);
  76564. if (batch.mustReturn) {
  76565. return;
  76566. }
  76567. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76568. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76569. var effect = _this._volumetricLightScatteringPass;
  76570. if (mesh === _this.mesh) {
  76571. if (subMesh.effect) {
  76572. effect = subMesh.effect;
  76573. }
  76574. else {
  76575. effect = material.getEffect();
  76576. }
  76577. }
  76578. engine.enableEffect(effect);
  76579. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76580. if (mesh === _this.mesh) {
  76581. material.bind(mesh.getWorldMatrix(), mesh);
  76582. }
  76583. else {
  76584. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76585. // Alpha test
  76586. if (material && material.needAlphaTesting()) {
  76587. var alphaTexture = material.getAlphaTestTexture();
  76588. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76589. if (alphaTexture) {
  76590. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76591. }
  76592. }
  76593. // Bones
  76594. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76595. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76596. }
  76597. }
  76598. // Draw
  76599. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76600. }
  76601. };
  76602. // Render target texture callbacks
  76603. var savedSceneClearColor;
  76604. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76605. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76606. savedSceneClearColor = scene.clearColor;
  76607. scene.clearColor = sceneClearColor;
  76608. });
  76609. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76610. scene.clearColor = savedSceneClearColor;
  76611. });
  76612. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76613. var engine = scene.getEngine();
  76614. var index;
  76615. if (depthOnlySubMeshes.length) {
  76616. engine.setColorWrite(false);
  76617. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76618. renderSubMesh(depthOnlySubMeshes.data[index]);
  76619. }
  76620. engine.setColorWrite(true);
  76621. }
  76622. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76623. renderSubMesh(opaqueSubMeshes.data[index]);
  76624. }
  76625. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76626. renderSubMesh(alphaTestSubMeshes.data[index]);
  76627. }
  76628. if (transparentSubMeshes.length) {
  76629. // Sort sub meshes
  76630. for (index = 0; index < transparentSubMeshes.length; index++) {
  76631. var submesh = transparentSubMeshes.data[index];
  76632. var boundingInfo = submesh.getBoundingInfo();
  76633. if (boundingInfo && scene.activeCamera) {
  76634. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76635. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76636. }
  76637. }
  76638. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76639. sortedArray.sort(function (a, b) {
  76640. // Alpha index first
  76641. if (a._alphaIndex > b._alphaIndex) {
  76642. return 1;
  76643. }
  76644. if (a._alphaIndex < b._alphaIndex) {
  76645. return -1;
  76646. }
  76647. // Then distance to camera
  76648. if (a._distanceToCamera < b._distanceToCamera) {
  76649. return 1;
  76650. }
  76651. if (a._distanceToCamera > b._distanceToCamera) {
  76652. return -1;
  76653. }
  76654. return 0;
  76655. });
  76656. // Render sub meshes
  76657. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76658. for (index = 0; index < sortedArray.length; index++) {
  76659. renderSubMesh(sortedArray[index]);
  76660. }
  76661. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76662. }
  76663. };
  76664. };
  76665. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76666. var transform = scene.getTransformMatrix();
  76667. var meshPosition;
  76668. if (this.useCustomMeshPosition) {
  76669. meshPosition = this.customMeshPosition;
  76670. }
  76671. else if (this.attachedNode) {
  76672. meshPosition = this.attachedNode.position;
  76673. }
  76674. else {
  76675. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76676. }
  76677. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76678. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76679. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76680. if (this.invert)
  76681. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76682. };
  76683. // Static methods
  76684. /**
  76685. * Creates a default mesh for the Volumeric Light Scattering post-process
  76686. * @param {string} The mesh name
  76687. * @param {BABYLON.Scene} The scene where to create the mesh
  76688. * @return {BABYLON.Mesh} the default mesh
  76689. */
  76690. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76691. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76692. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76693. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76694. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76695. mesh.material = material;
  76696. return mesh;
  76697. };
  76698. __decorate([
  76699. BABYLON.serializeAsVector3()
  76700. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76701. __decorate([
  76702. BABYLON.serialize()
  76703. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76704. __decorate([
  76705. BABYLON.serialize()
  76706. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76707. __decorate([
  76708. BABYLON.serializeAsMeshReference()
  76709. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76710. __decorate([
  76711. BABYLON.serialize()
  76712. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76713. __decorate([
  76714. BABYLON.serialize()
  76715. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76716. __decorate([
  76717. BABYLON.serialize()
  76718. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76719. __decorate([
  76720. BABYLON.serialize()
  76721. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76722. __decorate([
  76723. BABYLON.serialize()
  76724. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76725. return VolumetricLightScatteringPostProcess;
  76726. }(BABYLON.PostProcess));
  76727. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76728. })(BABYLON || (BABYLON = {}));
  76729. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76730. //
  76731. // This post-process allows the modification of rendered colors by using
  76732. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76733. //
  76734. // The object needs to be provided an url to a texture containing the color
  76735. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76736. // Use an image editing software to tweak the LUT to match your needs.
  76737. //
  76738. // For an example of a color LUT, see here:
  76739. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76740. // For explanations on color grading, see here:
  76741. // http://udn.epicgames.com/Three/ColorGrading.html
  76742. //
  76743. var BABYLON;
  76744. (function (BABYLON) {
  76745. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76746. __extends(ColorCorrectionPostProcess, _super);
  76747. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76748. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76749. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76750. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76751. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76752. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76753. _this.onApply = function (effect) {
  76754. effect.setTexture("colorTable", _this._colorTableTexture);
  76755. };
  76756. return _this;
  76757. }
  76758. return ColorCorrectionPostProcess;
  76759. }(BABYLON.PostProcess));
  76760. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76761. })(BABYLON || (BABYLON = {}));
  76762. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76763. var BABYLON;
  76764. (function (BABYLON) {
  76765. /** Defines operator used for tonemapping */
  76766. var TonemappingOperator;
  76767. (function (TonemappingOperator) {
  76768. /** Hable */
  76769. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76770. /** Reinhard */
  76771. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76772. /** HejiDawson */
  76773. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76774. /** Photographic */
  76775. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76776. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76777. ;
  76778. /**
  76779. * Defines a post process to apply tone mapping
  76780. */
  76781. var TonemapPostProcess = /** @class */ (function (_super) {
  76782. __extends(TonemapPostProcess, _super);
  76783. /**
  76784. * Creates a new TonemapPostProcess
  76785. * @param name defines the name of the postprocess
  76786. * @param _operator defines the operator to use
  76787. * @param exposureAdjustment defines the required exposure adjustement
  76788. * @param camera defines the camera to use (can be null)
  76789. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76790. * @param engine defines the hosting engine (can be ignore if camera is set)
  76791. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76792. */
  76793. function TonemapPostProcess(name, _operator,
  76794. /** Defines the required exposure adjustement */
  76795. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76796. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76797. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76798. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76799. _this._operator = _operator;
  76800. _this.exposureAdjustment = exposureAdjustment;
  76801. var defines = "#define ";
  76802. if (_this._operator === TonemappingOperator.Hable)
  76803. defines += "HABLE_TONEMAPPING";
  76804. else if (_this._operator === TonemappingOperator.Reinhard)
  76805. defines += "REINHARD_TONEMAPPING";
  76806. else if (_this._operator === TonemappingOperator.HejiDawson)
  76807. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76808. else if (_this._operator === TonemappingOperator.Photographic)
  76809. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76810. //sadly a second call to create the effect.
  76811. _this.updateEffect(defines);
  76812. _this.onApply = function (effect) {
  76813. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76814. };
  76815. return _this;
  76816. }
  76817. return TonemapPostProcess;
  76818. }(BABYLON.PostProcess));
  76819. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76820. })(BABYLON || (BABYLON = {}));
  76821. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76822. var BABYLON;
  76823. (function (BABYLON) {
  76824. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76825. __extends(DisplayPassPostProcess, _super);
  76826. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76827. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76828. }
  76829. return DisplayPassPostProcess;
  76830. }(BABYLON.PostProcess));
  76831. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76832. })(BABYLON || (BABYLON = {}));
  76833. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76834. var BABYLON;
  76835. (function (BABYLON) {
  76836. var HighlightsPostProcess = /** @class */ (function (_super) {
  76837. __extends(HighlightsPostProcess, _super);
  76838. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76839. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76840. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76841. }
  76842. return HighlightsPostProcess;
  76843. }(BABYLON.PostProcess));
  76844. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76845. })(BABYLON || (BABYLON = {}));
  76846. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76847. var BABYLON;
  76848. (function (BABYLON) {
  76849. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76850. __extends(ImageProcessingPostProcess, _super);
  76851. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76852. if (camera === void 0) { camera = null; }
  76853. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76854. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76855. _this._fromLinearSpace = true;
  76856. /**
  76857. * Defines cache preventing GC.
  76858. */
  76859. _this._defines = {
  76860. IMAGEPROCESSING: false,
  76861. VIGNETTE: false,
  76862. VIGNETTEBLENDMODEMULTIPLY: false,
  76863. VIGNETTEBLENDMODEOPAQUE: false,
  76864. TONEMAPPING: false,
  76865. CONTRAST: false,
  76866. COLORCURVES: false,
  76867. COLORGRADING: false,
  76868. COLORGRADING3D: false,
  76869. FROMLINEARSPACE: false,
  76870. SAMPLER3DGREENDEPTH: false,
  76871. SAMPLER3DBGRMAP: false,
  76872. IMAGEPROCESSINGPOSTPROCESS: false,
  76873. EXPOSURE: false,
  76874. };
  76875. // Setup the configuration as forced by the constructor. This would then not force the
  76876. // scene materials output in linear space and let untouched the default forward pass.
  76877. if (imageProcessingConfiguration) {
  76878. imageProcessingConfiguration.applyByPostProcess = true;
  76879. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76880. // This will cause the shader to be compiled
  76881. _this.fromLinearSpace = false;
  76882. }
  76883. // Setup the default processing configuration to the scene.
  76884. else {
  76885. _this._attachImageProcessingConfiguration(null, true);
  76886. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76887. }
  76888. _this.onApply = function (effect) {
  76889. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76890. };
  76891. return _this;
  76892. }
  76893. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76894. /**
  76895. * Gets the image processing configuration used either in this material.
  76896. */
  76897. get: function () {
  76898. return this._imageProcessingConfiguration;
  76899. },
  76900. /**
  76901. * Sets the Default image processing configuration used either in the this material.
  76902. *
  76903. * If sets to null, the scene one is in use.
  76904. */
  76905. set: function (value) {
  76906. this._attachImageProcessingConfiguration(value);
  76907. },
  76908. enumerable: true,
  76909. configurable: true
  76910. });
  76911. /**
  76912. * Attaches a new image processing configuration to the PBR Material.
  76913. * @param configuration
  76914. */
  76915. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76916. var _this = this;
  76917. if (doNotBuild === void 0) { doNotBuild = false; }
  76918. if (configuration === this._imageProcessingConfiguration) {
  76919. return;
  76920. }
  76921. // Detaches observer.
  76922. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76923. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76924. }
  76925. // Pick the scene configuration if needed.
  76926. if (!configuration) {
  76927. var scene = null;
  76928. var engine = this.getEngine();
  76929. var camera = this.getCamera();
  76930. if (camera) {
  76931. scene = camera.getScene();
  76932. }
  76933. else if (engine && engine.scenes) {
  76934. var scenes = engine.scenes;
  76935. scene = scenes[scenes.length - 1];
  76936. }
  76937. else {
  76938. scene = BABYLON.Engine.LastCreatedScene;
  76939. }
  76940. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76941. }
  76942. else {
  76943. this._imageProcessingConfiguration = configuration;
  76944. }
  76945. // Attaches observer.
  76946. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76947. _this._updateParameters();
  76948. });
  76949. // Ensure the effect will be rebuilt.
  76950. if (!doNotBuild) {
  76951. this._updateParameters();
  76952. }
  76953. };
  76954. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76955. /**
  76956. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76957. */
  76958. get: function () {
  76959. return this.imageProcessingConfiguration.colorCurves;
  76960. },
  76961. /**
  76962. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76963. */
  76964. set: function (value) {
  76965. this.imageProcessingConfiguration.colorCurves = value;
  76966. },
  76967. enumerable: true,
  76968. configurable: true
  76969. });
  76970. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76971. /**
  76972. * Gets wether the color curves effect is enabled.
  76973. */
  76974. get: function () {
  76975. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76976. },
  76977. /**
  76978. * Sets wether the color curves effect is enabled.
  76979. */
  76980. set: function (value) {
  76981. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76982. },
  76983. enumerable: true,
  76984. configurable: true
  76985. });
  76986. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76987. /**
  76988. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76989. */
  76990. get: function () {
  76991. return this.imageProcessingConfiguration.colorGradingTexture;
  76992. },
  76993. /**
  76994. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76995. */
  76996. set: function (value) {
  76997. this.imageProcessingConfiguration.colorGradingTexture = value;
  76998. },
  76999. enumerable: true,
  77000. configurable: true
  77001. });
  77002. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77003. /**
  77004. * Gets wether the color grading effect is enabled.
  77005. */
  77006. get: function () {
  77007. return this.imageProcessingConfiguration.colorGradingEnabled;
  77008. },
  77009. /**
  77010. * Gets wether the color grading effect is enabled.
  77011. */
  77012. set: function (value) {
  77013. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77014. },
  77015. enumerable: true,
  77016. configurable: true
  77017. });
  77018. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77019. /**
  77020. * Gets exposure used in the effect.
  77021. */
  77022. get: function () {
  77023. return this.imageProcessingConfiguration.exposure;
  77024. },
  77025. /**
  77026. * Sets exposure used in the effect.
  77027. */
  77028. set: function (value) {
  77029. this.imageProcessingConfiguration.exposure = value;
  77030. },
  77031. enumerable: true,
  77032. configurable: true
  77033. });
  77034. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77035. /**
  77036. * Gets wether tonemapping is enabled or not.
  77037. */
  77038. get: function () {
  77039. return this._imageProcessingConfiguration.toneMappingEnabled;
  77040. },
  77041. /**
  77042. * Sets wether tonemapping is enabled or not
  77043. */
  77044. set: function (value) {
  77045. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77046. },
  77047. enumerable: true,
  77048. configurable: true
  77049. });
  77050. ;
  77051. ;
  77052. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77053. /**
  77054. * Gets contrast used in the effect.
  77055. */
  77056. get: function () {
  77057. return this.imageProcessingConfiguration.contrast;
  77058. },
  77059. /**
  77060. * Sets contrast used in the effect.
  77061. */
  77062. set: function (value) {
  77063. this.imageProcessingConfiguration.contrast = value;
  77064. },
  77065. enumerable: true,
  77066. configurable: true
  77067. });
  77068. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77069. /**
  77070. * Gets Vignette stretch size.
  77071. */
  77072. get: function () {
  77073. return this.imageProcessingConfiguration.vignetteStretch;
  77074. },
  77075. /**
  77076. * Sets Vignette stretch size.
  77077. */
  77078. set: function (value) {
  77079. this.imageProcessingConfiguration.vignetteStretch = value;
  77080. },
  77081. enumerable: true,
  77082. configurable: true
  77083. });
  77084. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77085. /**
  77086. * Gets Vignette centre X Offset.
  77087. */
  77088. get: function () {
  77089. return this.imageProcessingConfiguration.vignetteCentreX;
  77090. },
  77091. /**
  77092. * Sets Vignette centre X Offset.
  77093. */
  77094. set: function (value) {
  77095. this.imageProcessingConfiguration.vignetteCentreX = value;
  77096. },
  77097. enumerable: true,
  77098. configurable: true
  77099. });
  77100. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77101. /**
  77102. * Gets Vignette centre Y Offset.
  77103. */
  77104. get: function () {
  77105. return this.imageProcessingConfiguration.vignetteCentreY;
  77106. },
  77107. /**
  77108. * Sets Vignette centre Y Offset.
  77109. */
  77110. set: function (value) {
  77111. this.imageProcessingConfiguration.vignetteCentreY = value;
  77112. },
  77113. enumerable: true,
  77114. configurable: true
  77115. });
  77116. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77117. /**
  77118. * Gets Vignette weight or intensity of the vignette effect.
  77119. */
  77120. get: function () {
  77121. return this.imageProcessingConfiguration.vignetteWeight;
  77122. },
  77123. /**
  77124. * Sets Vignette weight or intensity of the vignette effect.
  77125. */
  77126. set: function (value) {
  77127. this.imageProcessingConfiguration.vignetteWeight = value;
  77128. },
  77129. enumerable: true,
  77130. configurable: true
  77131. });
  77132. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77133. /**
  77134. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77135. * if vignetteEnabled is set to true.
  77136. */
  77137. get: function () {
  77138. return this.imageProcessingConfiguration.vignetteColor;
  77139. },
  77140. /**
  77141. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77142. * if vignetteEnabled is set to true.
  77143. */
  77144. set: function (value) {
  77145. this.imageProcessingConfiguration.vignetteColor = value;
  77146. },
  77147. enumerable: true,
  77148. configurable: true
  77149. });
  77150. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77151. /**
  77152. * Gets Camera field of view used by the Vignette effect.
  77153. */
  77154. get: function () {
  77155. return this.imageProcessingConfiguration.vignetteCameraFov;
  77156. },
  77157. /**
  77158. * Sets Camera field of view used by the Vignette effect.
  77159. */
  77160. set: function (value) {
  77161. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77162. },
  77163. enumerable: true,
  77164. configurable: true
  77165. });
  77166. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77167. /**
  77168. * Gets the vignette blend mode allowing different kind of effect.
  77169. */
  77170. get: function () {
  77171. return this.imageProcessingConfiguration.vignetteBlendMode;
  77172. },
  77173. /**
  77174. * Sets the vignette blend mode allowing different kind of effect.
  77175. */
  77176. set: function (value) {
  77177. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77178. },
  77179. enumerable: true,
  77180. configurable: true
  77181. });
  77182. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77183. /**
  77184. * Gets wether the vignette effect is enabled.
  77185. */
  77186. get: function () {
  77187. return this.imageProcessingConfiguration.vignetteEnabled;
  77188. },
  77189. /**
  77190. * Sets wether the vignette effect is enabled.
  77191. */
  77192. set: function (value) {
  77193. this.imageProcessingConfiguration.vignetteEnabled = value;
  77194. },
  77195. enumerable: true,
  77196. configurable: true
  77197. });
  77198. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77199. /**
  77200. * Gets wether the input of the processing is in Gamma or Linear Space.
  77201. */
  77202. get: function () {
  77203. return this._fromLinearSpace;
  77204. },
  77205. /**
  77206. * Sets wether the input of the processing is in Gamma or Linear Space.
  77207. */
  77208. set: function (value) {
  77209. if (this._fromLinearSpace === value) {
  77210. return;
  77211. }
  77212. this._fromLinearSpace = value;
  77213. this._updateParameters();
  77214. },
  77215. enumerable: true,
  77216. configurable: true
  77217. });
  77218. ImageProcessingPostProcess.prototype.getClassName = function () {
  77219. return "ImageProcessingPostProcess";
  77220. };
  77221. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77222. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77223. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77224. var defines = "";
  77225. for (var define in this._defines) {
  77226. if (this._defines[define]) {
  77227. defines += "#define " + define + ";\r\n";
  77228. }
  77229. }
  77230. var samplers = ["textureSampler"];
  77231. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77232. var uniforms = ["scale"];
  77233. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77234. this.updateEffect(defines, uniforms, samplers);
  77235. };
  77236. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77237. _super.prototype.dispose.call(this, camera);
  77238. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77239. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77240. }
  77241. this.imageProcessingConfiguration.applyByPostProcess = false;
  77242. };
  77243. __decorate([
  77244. BABYLON.serialize()
  77245. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77246. return ImageProcessingPostProcess;
  77247. }(BABYLON.PostProcess));
  77248. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77249. })(BABYLON || (BABYLON = {}));
  77250. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77251. var BABYLON;
  77252. (function (BABYLON) {
  77253. /**
  77254. * Class used to store bone information
  77255. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77256. */
  77257. var Bone = /** @class */ (function (_super) {
  77258. __extends(Bone, _super);
  77259. /**
  77260. * Create a new bone
  77261. * @param name defines the bone name
  77262. * @param skeleton defines the parent skeleton
  77263. * @param parentBone defines the parent (can be null if the bone is the root)
  77264. * @param localMatrix defines the local matrix
  77265. * @param restPose defines the rest pose matrix
  77266. * @param baseMatrix defines the base matrix
  77267. * @param index defines index of the bone in the hiearchy
  77268. */
  77269. function Bone(
  77270. /**
  77271. * defines the bone name
  77272. */
  77273. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77274. if (parentBone === void 0) { parentBone = null; }
  77275. if (localMatrix === void 0) { localMatrix = null; }
  77276. if (restPose === void 0) { restPose = null; }
  77277. if (baseMatrix === void 0) { baseMatrix = null; }
  77278. if (index === void 0) { index = null; }
  77279. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77280. _this.name = name;
  77281. /**
  77282. * Gets the list of child bones
  77283. */
  77284. _this.children = new Array();
  77285. /** Gets the animations associated with this bone */
  77286. _this.animations = new Array();
  77287. /**
  77288. * @hidden Internal only
  77289. * Set this value to map this bone to a different index in the transform matrices
  77290. * Set this value to -1 to exclude the bone from the transform matrices
  77291. */
  77292. _this._index = null;
  77293. _this._absoluteTransform = new BABYLON.Matrix();
  77294. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77295. _this._scalingDeterminant = 1;
  77296. _this._worldTransform = new BABYLON.Matrix();
  77297. _this._needToDecompose = true;
  77298. _this._needToCompose = false;
  77299. _this._skeleton = skeleton;
  77300. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77301. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77302. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77303. _this._index = index;
  77304. skeleton.bones.push(_this);
  77305. _this.setParent(parentBone, false);
  77306. if (baseMatrix || localMatrix) {
  77307. _this._updateDifferenceMatrix();
  77308. }
  77309. return _this;
  77310. }
  77311. Object.defineProperty(Bone.prototype, "_matrix", {
  77312. /** @hidden */
  77313. get: function () {
  77314. this._compose();
  77315. return this._localMatrix;
  77316. },
  77317. /** @hidden */
  77318. set: function (value) {
  77319. this._localMatrix.copyFrom(value);
  77320. this._needToDecompose = true;
  77321. },
  77322. enumerable: true,
  77323. configurable: true
  77324. });
  77325. // Members
  77326. /**
  77327. * Gets the parent skeleton
  77328. * @returns a skeleton
  77329. */
  77330. Bone.prototype.getSkeleton = function () {
  77331. return this._skeleton;
  77332. };
  77333. /**
  77334. * Gets parent bone
  77335. * @returns a bone or null if the bone is the root of the bone hierarchy
  77336. */
  77337. Bone.prototype.getParent = function () {
  77338. return this._parent;
  77339. };
  77340. /**
  77341. * Sets the parent bone
  77342. * @param parent defines the parent (can be null if the bone is the root)
  77343. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77344. */
  77345. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77346. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77347. if (this._parent === parent) {
  77348. return;
  77349. }
  77350. if (this._parent) {
  77351. var index = this._parent.children.indexOf(this);
  77352. if (index !== -1) {
  77353. this._parent.children.splice(index, 1);
  77354. }
  77355. }
  77356. this._parent = parent;
  77357. if (this._parent) {
  77358. this._parent.children.push(this);
  77359. }
  77360. if (updateDifferenceMatrix) {
  77361. this._updateDifferenceMatrix();
  77362. }
  77363. this.markAsDirty();
  77364. };
  77365. /**
  77366. * Gets the local matrix
  77367. * @returns a matrix
  77368. */
  77369. Bone.prototype.getLocalMatrix = function () {
  77370. this._compose();
  77371. return this._localMatrix;
  77372. };
  77373. /**
  77374. * Gets the base matrix (initial matrix which remains unchanged)
  77375. * @returns a matrix
  77376. */
  77377. Bone.prototype.getBaseMatrix = function () {
  77378. return this._baseMatrix;
  77379. };
  77380. /**
  77381. * Gets the rest pose matrix
  77382. * @returns a matrix
  77383. */
  77384. Bone.prototype.getRestPose = function () {
  77385. return this._restPose;
  77386. };
  77387. /**
  77388. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77389. */
  77390. Bone.prototype.getWorldMatrix = function () {
  77391. return this._worldTransform;
  77392. };
  77393. /**
  77394. * Sets the local matrix to rest pose matrix
  77395. */
  77396. Bone.prototype.returnToRest = function () {
  77397. this.updateMatrix(this._restPose.clone());
  77398. };
  77399. /**
  77400. * Gets the inverse of the absolute transform matrix.
  77401. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77402. * @returns a matrix
  77403. */
  77404. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77405. return this._invertedAbsoluteTransform;
  77406. };
  77407. /**
  77408. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77409. * @returns a matrix
  77410. */
  77411. Bone.prototype.getAbsoluteTransform = function () {
  77412. return this._absoluteTransform;
  77413. };
  77414. Object.defineProperty(Bone.prototype, "position", {
  77415. // Properties (matches AbstractMesh properties)
  77416. /** Gets or sets current position (in local space) */
  77417. get: function () {
  77418. this._decompose();
  77419. return this._localPosition;
  77420. },
  77421. set: function (newPosition) {
  77422. this._decompose();
  77423. this._localPosition.copyFrom(newPosition);
  77424. this._markAsDirtyAndCompose();
  77425. },
  77426. enumerable: true,
  77427. configurable: true
  77428. });
  77429. Object.defineProperty(Bone.prototype, "rotation", {
  77430. /** Gets or sets current rotation (in local space) */
  77431. get: function () {
  77432. return this.getRotation();
  77433. },
  77434. set: function (newRotation) {
  77435. this.setRotation(newRotation);
  77436. },
  77437. enumerable: true,
  77438. configurable: true
  77439. });
  77440. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77441. /** Gets or sets current rotation quaternion (in local space) */
  77442. get: function () {
  77443. this._decompose();
  77444. return this._localRotation;
  77445. },
  77446. set: function (newRotation) {
  77447. this.setRotationQuaternion(newRotation);
  77448. },
  77449. enumerable: true,
  77450. configurable: true
  77451. });
  77452. Object.defineProperty(Bone.prototype, "scaling", {
  77453. /** Gets or sets current scaling (in local space) */
  77454. get: function () {
  77455. return this.getScale();
  77456. },
  77457. set: function (newScaling) {
  77458. this.setScale(newScaling);
  77459. },
  77460. enumerable: true,
  77461. configurable: true
  77462. });
  77463. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77464. /**
  77465. * Gets the animation properties override
  77466. */
  77467. get: function () {
  77468. return this._skeleton.animationPropertiesOverride;
  77469. },
  77470. enumerable: true,
  77471. configurable: true
  77472. });
  77473. // Methods
  77474. Bone.prototype._decompose = function () {
  77475. if (!this._needToDecompose) {
  77476. return;
  77477. }
  77478. this._needToDecompose = false;
  77479. if (!this._localScaling) {
  77480. this._localScaling = BABYLON.Vector3.Zero();
  77481. this._localRotation = BABYLON.Quaternion.Zero();
  77482. this._localPosition = BABYLON.Vector3.Zero();
  77483. }
  77484. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77485. };
  77486. Bone.prototype._compose = function () {
  77487. if (!this._needToCompose) {
  77488. return;
  77489. }
  77490. this._needToCompose = false;
  77491. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77492. };
  77493. /**
  77494. * Update the base and local matrices
  77495. * @param matrix defines the new base or local matrix
  77496. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77497. * @param updateLocalMatrix defines if the local matrix should be updated
  77498. */
  77499. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77500. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77501. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77502. this._baseMatrix.copyFrom(matrix);
  77503. if (updateDifferenceMatrix) {
  77504. this._updateDifferenceMatrix();
  77505. }
  77506. if (updateLocalMatrix) {
  77507. this._localMatrix.copyFrom(matrix);
  77508. this._markAsDirtyAndDecompose();
  77509. }
  77510. else {
  77511. this.markAsDirty();
  77512. }
  77513. };
  77514. /** @hidden */
  77515. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77516. if (updateChildren === void 0) { updateChildren = true; }
  77517. if (!rootMatrix) {
  77518. rootMatrix = this._baseMatrix;
  77519. }
  77520. if (this._parent) {
  77521. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77522. }
  77523. else {
  77524. this._absoluteTransform.copyFrom(rootMatrix);
  77525. }
  77526. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77527. if (updateChildren) {
  77528. for (var index = 0; index < this.children.length; index++) {
  77529. this.children[index]._updateDifferenceMatrix();
  77530. }
  77531. }
  77532. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77533. };
  77534. /**
  77535. * Flag the bone as dirty (Forcing it to update everything)
  77536. */
  77537. Bone.prototype.markAsDirty = function () {
  77538. this._currentRenderId++;
  77539. this._childRenderId++;
  77540. this._skeleton._markAsDirty();
  77541. };
  77542. Bone.prototype._markAsDirtyAndCompose = function () {
  77543. this.markAsDirty();
  77544. this._needToCompose = true;
  77545. };
  77546. Bone.prototype._markAsDirtyAndDecompose = function () {
  77547. this.markAsDirty();
  77548. this._needToDecompose = true;
  77549. };
  77550. /**
  77551. * Copy an animation range from another bone
  77552. * @param source defines the source bone
  77553. * @param rangeName defines the range name to copy
  77554. * @param frameOffset defines the frame offset
  77555. * @param rescaleAsRequired defines if rescaling must be applied if required
  77556. * @param skelDimensionsRatio defines the scaling ratio
  77557. * @returns true if operation was successful
  77558. */
  77559. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77560. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77561. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77562. // all animation may be coming from a library skeleton, so may need to create animation
  77563. if (this.animations.length === 0) {
  77564. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77565. this.animations[0].setKeys([]);
  77566. }
  77567. // get animation info / verify there is such a range from the source bone
  77568. var sourceRange = source.animations[0].getRange(rangeName);
  77569. if (!sourceRange) {
  77570. return false;
  77571. }
  77572. var from = sourceRange.from;
  77573. var to = sourceRange.to;
  77574. var sourceKeys = source.animations[0].getKeys();
  77575. // rescaling prep
  77576. var sourceBoneLength = source.length;
  77577. var sourceParent = source.getParent();
  77578. var parent = this.getParent();
  77579. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77580. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77581. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77582. var destKeys = this.animations[0].getKeys();
  77583. // loop vars declaration
  77584. var orig;
  77585. var origTranslation;
  77586. var mat;
  77587. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77588. orig = sourceKeys[key];
  77589. if (orig.frame >= from && orig.frame <= to) {
  77590. if (rescaleAsRequired) {
  77591. mat = orig.value.clone();
  77592. // scale based on parent ratio, when bone has parent
  77593. if (parentScalingReqd) {
  77594. origTranslation = mat.getTranslation();
  77595. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77596. // scale based on skeleton dimension ratio when root bone, and value is passed
  77597. }
  77598. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77599. origTranslation = mat.getTranslation();
  77600. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77601. // use original when root bone, and no data for skelDimensionsRatio
  77602. }
  77603. else {
  77604. mat = orig.value;
  77605. }
  77606. }
  77607. else {
  77608. mat = orig.value;
  77609. }
  77610. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77611. }
  77612. }
  77613. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77614. return true;
  77615. };
  77616. /**
  77617. * Translate the bone in local or world space
  77618. * @param vec The amount to translate the bone
  77619. * @param space The space that the translation is in
  77620. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77621. */
  77622. Bone.prototype.translate = function (vec, space, mesh) {
  77623. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77624. var lm = this.getLocalMatrix();
  77625. if (space == BABYLON.Space.LOCAL) {
  77626. lm.m[12] += vec.x;
  77627. lm.m[13] += vec.y;
  77628. lm.m[14] += vec.z;
  77629. }
  77630. else {
  77631. var wm = null;
  77632. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77633. if (mesh) {
  77634. wm = mesh.getWorldMatrix();
  77635. }
  77636. this._skeleton.computeAbsoluteTransforms();
  77637. var tmat = Bone._tmpMats[0];
  77638. var tvec = Bone._tmpVecs[0];
  77639. if (this._parent) {
  77640. if (mesh && wm) {
  77641. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77642. tmat.multiplyToRef(wm, tmat);
  77643. }
  77644. else {
  77645. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77646. }
  77647. }
  77648. tmat.m[12] = 0;
  77649. tmat.m[13] = 0;
  77650. tmat.m[14] = 0;
  77651. tmat.invert();
  77652. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77653. lm.m[12] += tvec.x;
  77654. lm.m[13] += tvec.y;
  77655. lm.m[14] += tvec.z;
  77656. }
  77657. this._markAsDirtyAndDecompose();
  77658. };
  77659. /**
  77660. * Set the postion of the bone in local or world space
  77661. * @param position The position to set the bone
  77662. * @param space The space that the position is in
  77663. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77664. */
  77665. Bone.prototype.setPosition = function (position, space, mesh) {
  77666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77667. var lm = this.getLocalMatrix();
  77668. if (space == BABYLON.Space.LOCAL) {
  77669. lm.m[12] = position.x;
  77670. lm.m[13] = position.y;
  77671. lm.m[14] = position.z;
  77672. }
  77673. else {
  77674. var wm = null;
  77675. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77676. if (mesh) {
  77677. wm = mesh.getWorldMatrix();
  77678. }
  77679. this._skeleton.computeAbsoluteTransforms();
  77680. var tmat = Bone._tmpMats[0];
  77681. var vec = Bone._tmpVecs[0];
  77682. if (this._parent) {
  77683. if (mesh && wm) {
  77684. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77685. tmat.multiplyToRef(wm, tmat);
  77686. }
  77687. else {
  77688. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77689. }
  77690. }
  77691. tmat.invert();
  77692. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77693. lm.m[12] = vec.x;
  77694. lm.m[13] = vec.y;
  77695. lm.m[14] = vec.z;
  77696. }
  77697. this._markAsDirtyAndDecompose();
  77698. };
  77699. /**
  77700. * Set the absolute position of the bone (world space)
  77701. * @param position The position to set the bone
  77702. * @param mesh The mesh that this bone is attached to
  77703. */
  77704. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77705. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77706. };
  77707. /**
  77708. * Scale the bone on the x, y and z axes (in local space)
  77709. * @param x The amount to scale the bone on the x axis
  77710. * @param y The amount to scale the bone on the y axis
  77711. * @param z The amount to scale the bone on the z axis
  77712. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77713. */
  77714. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77715. if (scaleChildren === void 0) { scaleChildren = false; }
  77716. var locMat = this.getLocalMatrix();
  77717. // Apply new scaling on top of current local matrix
  77718. var scaleMat = Bone._tmpMats[0];
  77719. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77720. scaleMat.multiplyToRef(locMat, locMat);
  77721. // Invert scaling matrix and apply the inverse to all children
  77722. scaleMat.invert();
  77723. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77724. var child = _a[_i];
  77725. var cm = child.getLocalMatrix();
  77726. cm.multiplyToRef(scaleMat, cm);
  77727. cm.m[12] *= x;
  77728. cm.m[13] *= y;
  77729. cm.m[14] *= z;
  77730. child._markAsDirtyAndDecompose();
  77731. }
  77732. this._markAsDirtyAndDecompose();
  77733. if (scaleChildren) {
  77734. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77735. var child = _c[_b];
  77736. child.scale(x, y, z, scaleChildren);
  77737. }
  77738. }
  77739. };
  77740. /**
  77741. * Set the bone scaling in local space
  77742. * @param scale defines the scaling vector
  77743. */
  77744. Bone.prototype.setScale = function (scale) {
  77745. this._decompose();
  77746. this._localScaling.copyFrom(scale);
  77747. this._markAsDirtyAndCompose();
  77748. };
  77749. /**
  77750. * Gets the current scaling in local space
  77751. * @returns the current scaling vector
  77752. */
  77753. Bone.prototype.getScale = function () {
  77754. this._decompose();
  77755. return this._localScaling;
  77756. };
  77757. /**
  77758. * Gets the current scaling in local space and stores it in a target vector
  77759. * @param result defines the target vector
  77760. */
  77761. Bone.prototype.getScaleToRef = function (result) {
  77762. this._decompose();
  77763. result.copyFrom(this._localScaling);
  77764. };
  77765. /**
  77766. * Set the yaw, pitch, and roll of the bone in local or world space
  77767. * @param yaw The rotation of the bone on the y axis
  77768. * @param pitch The rotation of the bone on the x axis
  77769. * @param roll The rotation of the bone on the z axis
  77770. * @param space The space that the axes of rotation are in
  77771. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77772. */
  77773. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77774. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77775. if (space === BABYLON.Space.LOCAL) {
  77776. var quat = Bone._tmpQuat;
  77777. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77778. this.setRotationQuaternion(quat, space, mesh);
  77779. return;
  77780. }
  77781. var rotMatInv = Bone._tmpMats[0];
  77782. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77783. return;
  77784. }
  77785. var rotMat = Bone._tmpMats[1];
  77786. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77787. rotMatInv.multiplyToRef(rotMat, rotMat);
  77788. this._rotateWithMatrix(rotMat, space, mesh);
  77789. };
  77790. /**
  77791. * Add a rotation to the bone on an axis in local or world space
  77792. * @param axis The axis to rotate the bone on
  77793. * @param amount The amount to rotate the bone
  77794. * @param space The space that the axis is in
  77795. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77796. */
  77797. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77798. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77799. var rmat = Bone._tmpMats[0];
  77800. rmat.m[12] = 0;
  77801. rmat.m[13] = 0;
  77802. rmat.m[14] = 0;
  77803. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77804. this._rotateWithMatrix(rmat, space, mesh);
  77805. };
  77806. /**
  77807. * Set the rotation of the bone to a particular axis angle in local or world space
  77808. * @param axis The axis to rotate the bone on
  77809. * @param angle The angle that the bone should be rotated to
  77810. * @param space The space that the axis is in
  77811. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77812. */
  77813. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77814. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77815. if (space === BABYLON.Space.LOCAL) {
  77816. var quat = Bone._tmpQuat;
  77817. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77818. this.setRotationQuaternion(quat, space, mesh);
  77819. return;
  77820. }
  77821. var rotMatInv = Bone._tmpMats[0];
  77822. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77823. return;
  77824. }
  77825. var rotMat = Bone._tmpMats[1];
  77826. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77827. rotMatInv.multiplyToRef(rotMat, rotMat);
  77828. this._rotateWithMatrix(rotMat, space, mesh);
  77829. };
  77830. /**
  77831. * Set the euler rotation of the bone in local of world space
  77832. * @param rotation The euler rotation that the bone should be set to
  77833. * @param space The space that the rotation is in
  77834. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77835. */
  77836. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77837. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77838. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77839. };
  77840. /**
  77841. * Set the quaternion rotation of the bone in local of world space
  77842. * @param quat The quaternion rotation that the bone should be set to
  77843. * @param space The space that the rotation is in
  77844. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77845. */
  77846. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77847. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77848. if (space === BABYLON.Space.LOCAL) {
  77849. this._decompose();
  77850. this._localRotation.copyFrom(quat);
  77851. this._markAsDirtyAndCompose();
  77852. return;
  77853. }
  77854. var rotMatInv = Bone._tmpMats[0];
  77855. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77856. return;
  77857. }
  77858. var rotMat = Bone._tmpMats[1];
  77859. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77860. rotMatInv.multiplyToRef(rotMat, rotMat);
  77861. this._rotateWithMatrix(rotMat, space, mesh);
  77862. };
  77863. /**
  77864. * Set the rotation matrix of the bone in local of world space
  77865. * @param rotMat The rotation matrix that the bone should be set to
  77866. * @param space The space that the rotation is in
  77867. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77868. */
  77869. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77870. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77871. if (space === BABYLON.Space.LOCAL) {
  77872. var quat = Bone._tmpQuat;
  77873. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77874. this.setRotationQuaternion(quat, space, mesh);
  77875. return;
  77876. }
  77877. var rotMatInv = Bone._tmpMats[0];
  77878. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77879. return;
  77880. }
  77881. var rotMat2 = Bone._tmpMats[1];
  77882. rotMat2.copyFrom(rotMat);
  77883. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77884. this._rotateWithMatrix(rotMat2, space, mesh);
  77885. };
  77886. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77887. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77888. var lmat = this.getLocalMatrix();
  77889. var lx = lmat.m[12];
  77890. var ly = lmat.m[13];
  77891. var lz = lmat.m[14];
  77892. var parent = this.getParent();
  77893. var parentScale = Bone._tmpMats[3];
  77894. var parentScaleInv = Bone._tmpMats[4];
  77895. if (parent && space == BABYLON.Space.WORLD) {
  77896. if (mesh) {
  77897. parentScale.copyFrom(mesh.getWorldMatrix());
  77898. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77899. }
  77900. else {
  77901. parentScale.copyFrom(parent.getAbsoluteTransform());
  77902. }
  77903. parentScaleInv.copyFrom(parentScale);
  77904. parentScaleInv.invert();
  77905. lmat.multiplyToRef(parentScale, lmat);
  77906. lmat.multiplyToRef(rmat, lmat);
  77907. lmat.multiplyToRef(parentScaleInv, lmat);
  77908. }
  77909. else {
  77910. if (space == BABYLON.Space.WORLD && mesh) {
  77911. parentScale.copyFrom(mesh.getWorldMatrix());
  77912. parentScaleInv.copyFrom(parentScale);
  77913. parentScaleInv.invert();
  77914. lmat.multiplyToRef(parentScale, lmat);
  77915. lmat.multiplyToRef(rmat, lmat);
  77916. lmat.multiplyToRef(parentScaleInv, lmat);
  77917. }
  77918. else {
  77919. lmat.multiplyToRef(rmat, lmat);
  77920. }
  77921. }
  77922. lmat.m[12] = lx;
  77923. lmat.m[13] = ly;
  77924. lmat.m[14] = lz;
  77925. this.computeAbsoluteTransforms();
  77926. this._markAsDirtyAndDecompose();
  77927. };
  77928. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77929. var scaleMatrix = Bone._tmpMats[2];
  77930. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77931. if (mesh) {
  77932. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77933. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77934. }
  77935. rotMatInv.invert();
  77936. if (isNaN(rotMatInv.m[0])) {
  77937. // Matrix failed to invert.
  77938. // This can happen if scale is zero for example.
  77939. return false;
  77940. }
  77941. scaleMatrix.m[0] *= this._scalingDeterminant;
  77942. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77943. return true;
  77944. };
  77945. /**
  77946. * Get the position of the bone in local or world space
  77947. * @param space The space that the returned position is in
  77948. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77949. * @returns The position of the bone
  77950. */
  77951. Bone.prototype.getPosition = function (space, mesh) {
  77952. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77953. if (mesh === void 0) { mesh = null; }
  77954. var pos = BABYLON.Vector3.Zero();
  77955. this.getPositionToRef(space, mesh, pos);
  77956. return pos;
  77957. };
  77958. /**
  77959. * Copy the position of the bone to a vector3 in local or world space
  77960. * @param space The space that the returned position is in
  77961. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77962. * @param result The vector3 to copy the position to
  77963. */
  77964. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77965. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77966. if (space == BABYLON.Space.LOCAL) {
  77967. var lm = this.getLocalMatrix();
  77968. result.x = lm.m[12];
  77969. result.y = lm.m[13];
  77970. result.z = lm.m[14];
  77971. }
  77972. else {
  77973. var wm = null;
  77974. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77975. if (mesh) {
  77976. wm = mesh.getWorldMatrix();
  77977. }
  77978. this._skeleton.computeAbsoluteTransforms();
  77979. var tmat = Bone._tmpMats[0];
  77980. if (mesh && wm) {
  77981. tmat.copyFrom(this.getAbsoluteTransform());
  77982. tmat.multiplyToRef(wm, tmat);
  77983. }
  77984. else {
  77985. tmat = this.getAbsoluteTransform();
  77986. }
  77987. result.x = tmat.m[12];
  77988. result.y = tmat.m[13];
  77989. result.z = tmat.m[14];
  77990. }
  77991. };
  77992. /**
  77993. * Get the absolute position of the bone (world space)
  77994. * @param mesh The mesh that this bone is attached to
  77995. * @returns The absolute position of the bone
  77996. */
  77997. Bone.prototype.getAbsolutePosition = function (mesh) {
  77998. if (mesh === void 0) { mesh = null; }
  77999. var pos = BABYLON.Vector3.Zero();
  78000. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78001. return pos;
  78002. };
  78003. /**
  78004. * Copy the absolute position of the bone (world space) to the result param
  78005. * @param mesh The mesh that this bone is attached to
  78006. * @param result The vector3 to copy the absolute position to
  78007. */
  78008. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78009. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78010. };
  78011. /**
  78012. * Compute the absolute transforms of this bone and its children
  78013. */
  78014. Bone.prototype.computeAbsoluteTransforms = function () {
  78015. this._compose();
  78016. if (this._parent) {
  78017. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78018. }
  78019. else {
  78020. this._absoluteTransform.copyFrom(this._localMatrix);
  78021. var poseMatrix = this._skeleton.getPoseMatrix();
  78022. if (poseMatrix) {
  78023. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78024. }
  78025. }
  78026. var children = this.children;
  78027. var len = children.length;
  78028. for (var i = 0; i < len; i++) {
  78029. children[i].computeAbsoluteTransforms();
  78030. }
  78031. };
  78032. /**
  78033. * Get the world direction from an axis that is in the local space of the bone
  78034. * @param localAxis The local direction that is used to compute the world direction
  78035. * @param mesh The mesh that this bone is attached to
  78036. * @returns The world direction
  78037. */
  78038. Bone.prototype.getDirection = function (localAxis, mesh) {
  78039. if (mesh === void 0) { mesh = null; }
  78040. var result = BABYLON.Vector3.Zero();
  78041. this.getDirectionToRef(localAxis, mesh, result);
  78042. return result;
  78043. };
  78044. /**
  78045. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78046. * @param localAxis The local direction that is used to compute the world direction
  78047. * @param mesh The mesh that this bone is attached to
  78048. * @param result The vector3 that the world direction will be copied to
  78049. */
  78050. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78051. if (mesh === void 0) { mesh = null; }
  78052. var wm = null;
  78053. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78054. if (mesh) {
  78055. wm = mesh.getWorldMatrix();
  78056. }
  78057. this._skeleton.computeAbsoluteTransforms();
  78058. var mat = Bone._tmpMats[0];
  78059. mat.copyFrom(this.getAbsoluteTransform());
  78060. if (mesh && wm) {
  78061. mat.multiplyToRef(wm, mat);
  78062. }
  78063. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78064. result.normalize();
  78065. };
  78066. /**
  78067. * Get the euler rotation of the bone in local or world space
  78068. * @param space The space that the rotation should be in
  78069. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78070. * @returns The euler rotation
  78071. */
  78072. Bone.prototype.getRotation = function (space, mesh) {
  78073. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78074. if (mesh === void 0) { mesh = null; }
  78075. var result = BABYLON.Vector3.Zero();
  78076. this.getRotationToRef(space, mesh, result);
  78077. return result;
  78078. };
  78079. /**
  78080. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78081. * @param space The space that the rotation should be in
  78082. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78083. * @param result The vector3 that the rotation should be copied to
  78084. */
  78085. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78086. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78087. if (mesh === void 0) { mesh = null; }
  78088. var quat = Bone._tmpQuat;
  78089. this.getRotationQuaternionToRef(space, mesh, quat);
  78090. quat.toEulerAnglesToRef(result);
  78091. };
  78092. /**
  78093. * Get the quaternion rotation of the bone in either local or world space
  78094. * @param space The space that the rotation should be in
  78095. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78096. * @returns The quaternion rotation
  78097. */
  78098. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78099. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78100. if (mesh === void 0) { mesh = null; }
  78101. var result = BABYLON.Quaternion.Identity();
  78102. this.getRotationQuaternionToRef(space, mesh, result);
  78103. return result;
  78104. };
  78105. /**
  78106. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78107. * @param space The space that the rotation should be in
  78108. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78109. * @param result The quaternion that the rotation should be copied to
  78110. */
  78111. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78112. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78113. if (mesh === void 0) { mesh = null; }
  78114. if (space == BABYLON.Space.LOCAL) {
  78115. this._decompose();
  78116. result.copyFrom(this._localRotation);
  78117. }
  78118. else {
  78119. var mat = Bone._tmpMats[0];
  78120. var amat = this.getAbsoluteTransform();
  78121. if (mesh) {
  78122. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78123. }
  78124. else {
  78125. mat.copyFrom(amat);
  78126. }
  78127. mat.m[0] *= this._scalingDeterminant;
  78128. mat.m[1] *= this._scalingDeterminant;
  78129. mat.m[2] *= this._scalingDeterminant;
  78130. mat.decompose(undefined, result, undefined);
  78131. }
  78132. };
  78133. /**
  78134. * Get the rotation matrix of the bone in local or world space
  78135. * @param space The space that the rotation should be in
  78136. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78137. * @returns The rotation matrix
  78138. */
  78139. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78140. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78141. var result = BABYLON.Matrix.Identity();
  78142. this.getRotationMatrixToRef(space, mesh, result);
  78143. return result;
  78144. };
  78145. /**
  78146. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78147. * @param space The space that the rotation should be in
  78148. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78149. * @param result The quaternion that the rotation should be copied to
  78150. */
  78151. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78152. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78153. if (space == BABYLON.Space.LOCAL) {
  78154. this.getLocalMatrix().getRotationMatrixToRef(result);
  78155. }
  78156. else {
  78157. var mat = Bone._tmpMats[0];
  78158. var amat = this.getAbsoluteTransform();
  78159. if (mesh) {
  78160. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78161. }
  78162. else {
  78163. mat.copyFrom(amat);
  78164. }
  78165. mat.m[0] *= this._scalingDeterminant;
  78166. mat.m[1] *= this._scalingDeterminant;
  78167. mat.m[2] *= this._scalingDeterminant;
  78168. mat.getRotationMatrixToRef(result);
  78169. }
  78170. };
  78171. /**
  78172. * Get the world position of a point that is in the local space of the bone
  78173. * @param position The local position
  78174. * @param mesh The mesh that this bone is attached to
  78175. * @returns The world position
  78176. */
  78177. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78178. if (mesh === void 0) { mesh = null; }
  78179. var result = BABYLON.Vector3.Zero();
  78180. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78181. return result;
  78182. };
  78183. /**
  78184. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78185. * @param position The local position
  78186. * @param mesh The mesh that this bone is attached to
  78187. * @param result The vector3 that the world position should be copied to
  78188. */
  78189. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78190. if (mesh === void 0) { mesh = null; }
  78191. var wm = null;
  78192. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78193. if (mesh) {
  78194. wm = mesh.getWorldMatrix();
  78195. }
  78196. this._skeleton.computeAbsoluteTransforms();
  78197. var tmat = Bone._tmpMats[0];
  78198. if (mesh && wm) {
  78199. tmat.copyFrom(this.getAbsoluteTransform());
  78200. tmat.multiplyToRef(wm, tmat);
  78201. }
  78202. else {
  78203. tmat = this.getAbsoluteTransform();
  78204. }
  78205. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78206. };
  78207. /**
  78208. * Get the local position of a point that is in world space
  78209. * @param position The world position
  78210. * @param mesh The mesh that this bone is attached to
  78211. * @returns The local position
  78212. */
  78213. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78214. if (mesh === void 0) { mesh = null; }
  78215. var result = BABYLON.Vector3.Zero();
  78216. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78217. return result;
  78218. };
  78219. /**
  78220. * Get the local position of a point that is in world space and copy it to the result param
  78221. * @param position The world position
  78222. * @param mesh The mesh that this bone is attached to
  78223. * @param result The vector3 that the local position should be copied to
  78224. */
  78225. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78226. if (mesh === void 0) { mesh = null; }
  78227. var wm = null;
  78228. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78229. if (mesh) {
  78230. wm = mesh.getWorldMatrix();
  78231. }
  78232. this._skeleton.computeAbsoluteTransforms();
  78233. var tmat = Bone._tmpMats[0];
  78234. tmat.copyFrom(this.getAbsoluteTransform());
  78235. if (mesh && wm) {
  78236. tmat.multiplyToRef(wm, tmat);
  78237. }
  78238. tmat.invert();
  78239. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78240. };
  78241. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78242. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78243. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78244. return Bone;
  78245. }(BABYLON.Node));
  78246. BABYLON.Bone = Bone;
  78247. })(BABYLON || (BABYLON = {}));
  78248. //# sourceMappingURL=babylon.bone.js.map
  78249. var BABYLON;
  78250. (function (BABYLON) {
  78251. /**
  78252. * Class used to apply inverse kinematics to bones
  78253. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78254. */
  78255. var BoneIKController = /** @class */ (function () {
  78256. /**
  78257. * Creates a new BoneIKController
  78258. * @param mesh defines the mesh to control
  78259. * @param bone defines the bone to control
  78260. * @param options defines options to set up the controller
  78261. */
  78262. function BoneIKController(mesh, bone, options) {
  78263. /**
  78264. * Gets or sets the target position
  78265. */
  78266. this.targetPosition = BABYLON.Vector3.Zero();
  78267. /**
  78268. * Gets or sets the pole target position
  78269. */
  78270. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78271. /**
  78272. * Gets or sets the pole target local offset
  78273. */
  78274. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78275. /**
  78276. * Gets or sets the pole angle
  78277. */
  78278. this.poleAngle = 0;
  78279. /**
  78280. * 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)
  78281. */
  78282. this.slerpAmount = 1;
  78283. this._bone1Quat = BABYLON.Quaternion.Identity();
  78284. this._bone1Mat = BABYLON.Matrix.Identity();
  78285. this._bone2Ang = Math.PI;
  78286. this._maxAngle = Math.PI;
  78287. this._rightHandedSystem = false;
  78288. this._bendAxis = BABYLON.Vector3.Right();
  78289. this._slerping = false;
  78290. this._adjustRoll = 0;
  78291. this._bone2 = bone;
  78292. this._bone1 = bone.getParent();
  78293. if (!this._bone1) {
  78294. return;
  78295. }
  78296. this.mesh = mesh;
  78297. var bonePos = bone.getPosition();
  78298. if (bone.getAbsoluteTransform().determinant() > 0) {
  78299. this._rightHandedSystem = true;
  78300. this._bendAxis.x = 0;
  78301. this._bendAxis.y = 0;
  78302. this._bendAxis.z = -1;
  78303. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78304. this._adjustRoll = Math.PI * .5;
  78305. this._bendAxis.z = 1;
  78306. }
  78307. }
  78308. if (this._bone1.length) {
  78309. var boneScale1 = this._bone1.getScale();
  78310. var boneScale2 = this._bone2.getScale();
  78311. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78312. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78313. }
  78314. else if (this._bone1.children[0]) {
  78315. mesh.computeWorldMatrix(true);
  78316. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78317. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78318. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78319. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78320. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78321. }
  78322. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78323. this.maxAngle = Math.PI;
  78324. if (options) {
  78325. if (options.targetMesh) {
  78326. this.targetMesh = options.targetMesh;
  78327. this.targetMesh.computeWorldMatrix(true);
  78328. }
  78329. if (options.poleTargetMesh) {
  78330. this.poleTargetMesh = options.poleTargetMesh;
  78331. this.poleTargetMesh.computeWorldMatrix(true);
  78332. }
  78333. else if (options.poleTargetBone) {
  78334. this.poleTargetBone = options.poleTargetBone;
  78335. }
  78336. else if (this._bone1.getParent()) {
  78337. this.poleTargetBone = this._bone1.getParent();
  78338. }
  78339. if (options.poleTargetLocalOffset) {
  78340. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78341. }
  78342. if (options.poleAngle) {
  78343. this.poleAngle = options.poleAngle;
  78344. }
  78345. if (options.bendAxis) {
  78346. this._bendAxis.copyFrom(options.bendAxis);
  78347. }
  78348. if (options.maxAngle) {
  78349. this.maxAngle = options.maxAngle;
  78350. }
  78351. if (options.slerpAmount) {
  78352. this.slerpAmount = options.slerpAmount;
  78353. }
  78354. }
  78355. }
  78356. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78357. /**
  78358. * Gets or sets maximum allowed angle
  78359. */
  78360. get: function () {
  78361. return this._maxAngle;
  78362. },
  78363. set: function (value) {
  78364. this._setMaxAngle(value);
  78365. },
  78366. enumerable: true,
  78367. configurable: true
  78368. });
  78369. BoneIKController.prototype._setMaxAngle = function (ang) {
  78370. if (ang < 0) {
  78371. ang = 0;
  78372. }
  78373. if (ang > Math.PI || ang == undefined) {
  78374. ang = Math.PI;
  78375. }
  78376. this._maxAngle = ang;
  78377. var a = this._bone1Length;
  78378. var b = this._bone2Length;
  78379. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78380. };
  78381. /**
  78382. * Force the controller to update the bones
  78383. */
  78384. BoneIKController.prototype.update = function () {
  78385. var bone1 = this._bone1;
  78386. if (!bone1) {
  78387. return;
  78388. }
  78389. var target = this.targetPosition;
  78390. var poleTarget = this.poleTargetPosition;
  78391. var mat1 = BoneIKController._tmpMats[0];
  78392. var mat2 = BoneIKController._tmpMats[1];
  78393. if (this.targetMesh) {
  78394. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78395. }
  78396. if (this.poleTargetBone) {
  78397. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78398. }
  78399. else if (this.poleTargetMesh) {
  78400. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78401. }
  78402. var bonePos = BoneIKController._tmpVecs[0];
  78403. var zaxis = BoneIKController._tmpVecs[1];
  78404. var xaxis = BoneIKController._tmpVecs[2];
  78405. var yaxis = BoneIKController._tmpVecs[3];
  78406. var upAxis = BoneIKController._tmpVecs[4];
  78407. var _tmpQuat = BoneIKController._tmpQuat;
  78408. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78409. poleTarget.subtractToRef(bonePos, upAxis);
  78410. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78411. upAxis.y = 1;
  78412. }
  78413. else {
  78414. upAxis.normalize();
  78415. }
  78416. target.subtractToRef(bonePos, yaxis);
  78417. yaxis.normalize();
  78418. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78419. zaxis.normalize();
  78420. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78421. xaxis.normalize();
  78422. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78423. var a = this._bone1Length;
  78424. var b = this._bone2Length;
  78425. var c = BABYLON.Vector3.Distance(bonePos, target);
  78426. if (this._maxReach > 0) {
  78427. c = Math.min(this._maxReach, c);
  78428. }
  78429. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78430. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78431. if (acosa > 1) {
  78432. acosa = 1;
  78433. }
  78434. if (acosb > 1) {
  78435. acosb = 1;
  78436. }
  78437. if (acosa < -1) {
  78438. acosa = -1;
  78439. }
  78440. if (acosb < -1) {
  78441. acosb = -1;
  78442. }
  78443. var angA = Math.acos(acosa);
  78444. var angB = Math.acos(acosb);
  78445. var angC = -angA - angB;
  78446. if (this._rightHandedSystem) {
  78447. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78448. mat2.multiplyToRef(mat1, mat1);
  78449. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78450. mat2.multiplyToRef(mat1, mat1);
  78451. }
  78452. else {
  78453. var _tmpVec = BoneIKController._tmpVecs[5];
  78454. _tmpVec.copyFrom(this._bendAxis);
  78455. _tmpVec.x *= -1;
  78456. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78457. mat2.multiplyToRef(mat1, mat1);
  78458. }
  78459. if (this.poleAngle) {
  78460. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78461. mat1.multiplyToRef(mat2, mat1);
  78462. }
  78463. if (this._bone1) {
  78464. if (this.slerpAmount < 1) {
  78465. if (!this._slerping) {
  78466. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78467. }
  78468. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78469. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78470. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78471. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78472. this._slerping = true;
  78473. }
  78474. else {
  78475. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78476. this._bone1Mat.copyFrom(mat1);
  78477. this._slerping = false;
  78478. }
  78479. }
  78480. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78481. this._bone2Ang = angC;
  78482. };
  78483. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78484. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78485. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78486. return BoneIKController;
  78487. }());
  78488. BABYLON.BoneIKController = BoneIKController;
  78489. })(BABYLON || (BABYLON = {}));
  78490. //# sourceMappingURL=babylon.boneIKController.js.map
  78491. var BABYLON;
  78492. (function (BABYLON) {
  78493. /**
  78494. * Class used to make a bone look toward a point in space
  78495. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78496. */
  78497. var BoneLookController = /** @class */ (function () {
  78498. /**
  78499. * Create a BoneLookController
  78500. * @param mesh the mesh that the bone belongs to
  78501. * @param bone the bone that will be looking to the target
  78502. * @param target the target Vector3 to look at
  78503. * @param settings optional settings:
  78504. * * maxYaw: the maximum angle the bone will yaw to
  78505. * * minYaw: the minimum angle the bone will yaw to
  78506. * * maxPitch: the maximum angle the bone will pitch to
  78507. * * minPitch: the minimum angle the bone will yaw to
  78508. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78509. * * upAxis: the up axis of the coordinate system
  78510. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78511. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78512. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78513. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78514. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78515. * * adjustRoll: used to make an adjustment to the roll of the bone
  78516. **/
  78517. function BoneLookController(mesh, bone, target, options) {
  78518. /**
  78519. * The up axis of the coordinate system that is used when the bone is rotated
  78520. */
  78521. this.upAxis = BABYLON.Vector3.Up();
  78522. /**
  78523. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78524. */
  78525. this.upAxisSpace = BABYLON.Space.LOCAL;
  78526. /**
  78527. * Used to make an adjustment to the yaw of the bone
  78528. */
  78529. this.adjustYaw = 0;
  78530. /**
  78531. * Used to make an adjustment to the pitch of the bone
  78532. */
  78533. this.adjustPitch = 0;
  78534. /**
  78535. * Used to make an adjustment to the roll of the bone
  78536. */
  78537. this.adjustRoll = 0;
  78538. /**
  78539. * 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)
  78540. */
  78541. this.slerpAmount = 1;
  78542. this._boneQuat = BABYLON.Quaternion.Identity();
  78543. this._slerping = false;
  78544. this._firstFrameSkipped = false;
  78545. this._fowardAxis = BABYLON.Vector3.Forward();
  78546. this.mesh = mesh;
  78547. this.bone = bone;
  78548. this.target = target;
  78549. if (options) {
  78550. if (options.adjustYaw) {
  78551. this.adjustYaw = options.adjustYaw;
  78552. }
  78553. if (options.adjustPitch) {
  78554. this.adjustPitch = options.adjustPitch;
  78555. }
  78556. if (options.adjustRoll) {
  78557. this.adjustRoll = options.adjustRoll;
  78558. }
  78559. if (options.maxYaw != null) {
  78560. this.maxYaw = options.maxYaw;
  78561. }
  78562. else {
  78563. this.maxYaw = Math.PI;
  78564. }
  78565. if (options.minYaw != null) {
  78566. this.minYaw = options.minYaw;
  78567. }
  78568. else {
  78569. this.minYaw = -Math.PI;
  78570. }
  78571. if (options.maxPitch != null) {
  78572. this.maxPitch = options.maxPitch;
  78573. }
  78574. else {
  78575. this.maxPitch = Math.PI;
  78576. }
  78577. if (options.minPitch != null) {
  78578. this.minPitch = options.minPitch;
  78579. }
  78580. else {
  78581. this.minPitch = -Math.PI;
  78582. }
  78583. if (options.slerpAmount != null) {
  78584. this.slerpAmount = options.slerpAmount;
  78585. }
  78586. if (options.upAxis != null) {
  78587. this.upAxis = options.upAxis;
  78588. }
  78589. if (options.upAxisSpace != null) {
  78590. this.upAxisSpace = options.upAxisSpace;
  78591. }
  78592. if (options.yawAxis != null || options.pitchAxis != null) {
  78593. var newYawAxis = BABYLON.Axis.Y;
  78594. var newPitchAxis = BABYLON.Axis.X;
  78595. if (options.yawAxis != null) {
  78596. newYawAxis = options.yawAxis.clone();
  78597. newYawAxis.normalize();
  78598. }
  78599. if (options.pitchAxis != null) {
  78600. newPitchAxis = options.pitchAxis.clone();
  78601. newPitchAxis.normalize();
  78602. }
  78603. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78604. this._transformYawPitch = BABYLON.Matrix.Identity();
  78605. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78606. this._transformYawPitchInv = this._transformYawPitch.clone();
  78607. this._transformYawPitch.invert();
  78608. }
  78609. }
  78610. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78611. this.upAxisSpace = BABYLON.Space.LOCAL;
  78612. }
  78613. }
  78614. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78615. /**
  78616. * Gets or sets the minimum yaw angle that the bone can look to
  78617. */
  78618. get: function () {
  78619. return this._minYaw;
  78620. },
  78621. set: function (value) {
  78622. this._minYaw = value;
  78623. this._minYawSin = Math.sin(value);
  78624. this._minYawCos = Math.cos(value);
  78625. if (this._maxYaw != null) {
  78626. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78627. this._yawRange = this._maxYaw - this._minYaw;
  78628. }
  78629. },
  78630. enumerable: true,
  78631. configurable: true
  78632. });
  78633. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78634. /**
  78635. * Gets or sets the maximum yaw angle that the bone can look to
  78636. */
  78637. get: function () {
  78638. return this._maxYaw;
  78639. },
  78640. set: function (value) {
  78641. this._maxYaw = value;
  78642. this._maxYawSin = Math.sin(value);
  78643. this._maxYawCos = Math.cos(value);
  78644. if (this._minYaw != null) {
  78645. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78646. this._yawRange = this._maxYaw - this._minYaw;
  78647. }
  78648. },
  78649. enumerable: true,
  78650. configurable: true
  78651. });
  78652. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78653. /**
  78654. * Gets or sets the minimum pitch angle that the bone can look to
  78655. */
  78656. get: function () {
  78657. return this._minPitch;
  78658. },
  78659. set: function (value) {
  78660. this._minPitch = value;
  78661. this._minPitchTan = Math.tan(value);
  78662. },
  78663. enumerable: true,
  78664. configurable: true
  78665. });
  78666. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78667. /**
  78668. * Gets or sets the maximum pitch angle that the bone can look to
  78669. */
  78670. get: function () {
  78671. return this._maxPitch;
  78672. },
  78673. set: function (value) {
  78674. this._maxPitch = value;
  78675. this._maxPitchTan = Math.tan(value);
  78676. },
  78677. enumerable: true,
  78678. configurable: true
  78679. });
  78680. /**
  78681. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78682. */
  78683. BoneLookController.prototype.update = function () {
  78684. //skip the first frame when slerping so that the mesh rotation is correct
  78685. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78686. this._firstFrameSkipped = true;
  78687. return;
  78688. }
  78689. var bone = this.bone;
  78690. var bonePos = BoneLookController._tmpVecs[0];
  78691. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78692. var target = this.target;
  78693. var _tmpMat1 = BoneLookController._tmpMats[0];
  78694. var _tmpMat2 = BoneLookController._tmpMats[1];
  78695. var mesh = this.mesh;
  78696. var parentBone = bone.getParent();
  78697. var upAxis = BoneLookController._tmpVecs[1];
  78698. upAxis.copyFrom(this.upAxis);
  78699. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78700. if (this._transformYawPitch) {
  78701. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78702. }
  78703. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78704. }
  78705. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78706. mesh.getDirectionToRef(upAxis, upAxis);
  78707. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78708. upAxis.normalize();
  78709. }
  78710. }
  78711. var checkYaw = false;
  78712. var checkPitch = false;
  78713. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78714. checkYaw = true;
  78715. }
  78716. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78717. checkPitch = true;
  78718. }
  78719. if (checkYaw || checkPitch) {
  78720. var spaceMat = BoneLookController._tmpMats[2];
  78721. var spaceMatInv = BoneLookController._tmpMats[3];
  78722. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78723. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78724. }
  78725. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78726. spaceMat.copyFrom(mesh.getWorldMatrix());
  78727. }
  78728. else {
  78729. var forwardAxis = BoneLookController._tmpVecs[2];
  78730. forwardAxis.copyFrom(this._fowardAxis);
  78731. if (this._transformYawPitch) {
  78732. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78733. }
  78734. if (parentBone) {
  78735. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78736. }
  78737. else {
  78738. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78739. }
  78740. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78741. rightAxis.normalize();
  78742. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78743. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78744. }
  78745. spaceMat.invertToRef(spaceMatInv);
  78746. var xzlen = null;
  78747. if (checkPitch) {
  78748. var localTarget = BoneLookController._tmpVecs[3];
  78749. target.subtractToRef(bonePos, localTarget);
  78750. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78751. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78752. var pitch = Math.atan2(localTarget.y, xzlen);
  78753. var newPitch = pitch;
  78754. if (pitch > this._maxPitch) {
  78755. localTarget.y = this._maxPitchTan * xzlen;
  78756. newPitch = this._maxPitch;
  78757. }
  78758. else if (pitch < this._minPitch) {
  78759. localTarget.y = this._minPitchTan * xzlen;
  78760. newPitch = this._minPitch;
  78761. }
  78762. if (pitch != newPitch) {
  78763. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78764. localTarget.addInPlace(bonePos);
  78765. target = localTarget;
  78766. }
  78767. }
  78768. if (checkYaw) {
  78769. var localTarget = BoneLookController._tmpVecs[4];
  78770. target.subtractToRef(bonePos, localTarget);
  78771. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78772. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78773. var newYaw = yaw;
  78774. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78775. if (xzlen == null) {
  78776. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78777. }
  78778. if (this._yawRange > Math.PI) {
  78779. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78780. localTarget.z = this._maxYawCos * xzlen;
  78781. localTarget.x = this._maxYawSin * xzlen;
  78782. newYaw = this._maxYaw;
  78783. }
  78784. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78785. localTarget.z = this._minYawCos * xzlen;
  78786. localTarget.x = this._minYawSin * xzlen;
  78787. newYaw = this._minYaw;
  78788. }
  78789. }
  78790. else {
  78791. if (yaw > this._maxYaw) {
  78792. localTarget.z = this._maxYawCos * xzlen;
  78793. localTarget.x = this._maxYawSin * xzlen;
  78794. newYaw = this._maxYaw;
  78795. }
  78796. else if (yaw < this._minYaw) {
  78797. localTarget.z = this._minYawCos * xzlen;
  78798. localTarget.x = this._minYawSin * xzlen;
  78799. newYaw = this._minYaw;
  78800. }
  78801. }
  78802. }
  78803. if (this._slerping && this._yawRange > Math.PI) {
  78804. //are we going to be crossing into the min/max region?
  78805. var boneFwd = BoneLookController._tmpVecs[8];
  78806. boneFwd.copyFrom(BABYLON.Axis.Z);
  78807. if (this._transformYawPitch) {
  78808. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78809. }
  78810. var boneRotMat = BoneLookController._tmpMats[4];
  78811. this._boneQuat.toRotationMatrix(boneRotMat);
  78812. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78813. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78814. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78815. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78816. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78817. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78818. if (angBtwTar > angBtwMidYaw) {
  78819. if (xzlen == null) {
  78820. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78821. }
  78822. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78823. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78824. if (angBtwMin < angBtwMax) {
  78825. newYaw = boneYaw + Math.PI * .75;
  78826. localTarget.z = Math.cos(newYaw) * xzlen;
  78827. localTarget.x = Math.sin(newYaw) * xzlen;
  78828. }
  78829. else {
  78830. newYaw = boneYaw - Math.PI * .75;
  78831. localTarget.z = Math.cos(newYaw) * xzlen;
  78832. localTarget.x = Math.sin(newYaw) * xzlen;
  78833. }
  78834. }
  78835. }
  78836. if (yaw != newYaw) {
  78837. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78838. localTarget.addInPlace(bonePos);
  78839. target = localTarget;
  78840. }
  78841. }
  78842. }
  78843. var zaxis = BoneLookController._tmpVecs[5];
  78844. var xaxis = BoneLookController._tmpVecs[6];
  78845. var yaxis = BoneLookController._tmpVecs[7];
  78846. var _tmpQuat = BoneLookController._tmpQuat;
  78847. target.subtractToRef(bonePos, zaxis);
  78848. zaxis.normalize();
  78849. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78850. xaxis.normalize();
  78851. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78852. yaxis.normalize();
  78853. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78854. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78855. return;
  78856. }
  78857. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78858. return;
  78859. }
  78860. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78861. return;
  78862. }
  78863. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78864. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78865. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78866. }
  78867. if (this.slerpAmount < 1) {
  78868. if (!this._slerping) {
  78869. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78870. }
  78871. if (this._transformYawPitch) {
  78872. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78873. }
  78874. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78875. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78876. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78877. this._slerping = true;
  78878. }
  78879. else {
  78880. if (this._transformYawPitch) {
  78881. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78882. }
  78883. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78884. this._slerping = false;
  78885. }
  78886. };
  78887. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78888. var angDiff = ang2 - ang1;
  78889. angDiff %= Math.PI * 2;
  78890. if (angDiff > Math.PI) {
  78891. angDiff -= Math.PI * 2;
  78892. }
  78893. else if (angDiff < -Math.PI) {
  78894. angDiff += Math.PI * 2;
  78895. }
  78896. return angDiff;
  78897. };
  78898. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78899. ang1 %= (2 * Math.PI);
  78900. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78901. ang2 %= (2 * Math.PI);
  78902. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78903. var ab = 0;
  78904. if (ang1 < ang2) {
  78905. ab = ang2 - ang1;
  78906. }
  78907. else {
  78908. ab = ang1 - ang2;
  78909. }
  78910. if (ab > Math.PI) {
  78911. ab = Math.PI * 2 - ab;
  78912. }
  78913. return ab;
  78914. };
  78915. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78916. ang %= (2 * Math.PI);
  78917. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78918. ang1 %= (2 * Math.PI);
  78919. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78920. ang2 %= (2 * Math.PI);
  78921. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78922. if (ang1 < ang2) {
  78923. if (ang > ang1 && ang < ang2) {
  78924. return true;
  78925. }
  78926. }
  78927. else {
  78928. if (ang > ang2 && ang < ang1) {
  78929. return true;
  78930. }
  78931. }
  78932. return false;
  78933. };
  78934. 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()];
  78935. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78936. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78937. return BoneLookController;
  78938. }());
  78939. BABYLON.BoneLookController = BoneLookController;
  78940. })(BABYLON || (BABYLON = {}));
  78941. //# sourceMappingURL=babylon.boneLookController.js.map
  78942. var BABYLON;
  78943. (function (BABYLON) {
  78944. /**
  78945. * Class used to handle skinning animations
  78946. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78947. */
  78948. var Skeleton = /** @class */ (function () {
  78949. /**
  78950. * Creates a new skeleton
  78951. * @param name defines the skeleton name
  78952. * @param id defines the skeleton Id
  78953. * @param scene defines the hosting scene
  78954. */
  78955. function Skeleton(
  78956. /** defines the skeleton name */
  78957. name,
  78958. /** defines the skeleton Id */
  78959. id, scene) {
  78960. this.name = name;
  78961. this.id = id;
  78962. /**
  78963. * Gets the list of child bones
  78964. */
  78965. this.bones = new Array();
  78966. /**
  78967. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78968. */
  78969. this.needInitialSkinMatrix = false;
  78970. this._isDirty = true;
  78971. this._meshesWithPoseMatrix = new Array();
  78972. this._identity = BABYLON.Matrix.Identity();
  78973. this._ranges = {};
  78974. this._lastAbsoluteTransformsUpdateId = -1;
  78975. /**
  78976. * Specifies if the skeleton should be serialized
  78977. */
  78978. this.doNotSerialize = false;
  78979. this._animationPropertiesOverride = null;
  78980. // Events
  78981. /**
  78982. * An observable triggered before computing the skeleton's matrices
  78983. */
  78984. this.onBeforeComputeObservable = new BABYLON.Observable();
  78985. this.bones = [];
  78986. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78987. scene.skeletons.push(this);
  78988. //make sure it will recalculate the matrix next time prepare is called.
  78989. this._isDirty = true;
  78990. }
  78991. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78992. /**
  78993. * Gets or sets the animation properties override
  78994. */
  78995. get: function () {
  78996. if (!this._animationPropertiesOverride) {
  78997. return this._scene.animationPropertiesOverride;
  78998. }
  78999. return this._animationPropertiesOverride;
  79000. },
  79001. set: function (value) {
  79002. this._animationPropertiesOverride = value;
  79003. },
  79004. enumerable: true,
  79005. configurable: true
  79006. });
  79007. // Members
  79008. /**
  79009. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79010. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79011. * @returns a Float32Array containing matrices data
  79012. */
  79013. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79014. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79015. return mesh._bonesTransformMatrices;
  79016. }
  79017. if (!this._transformMatrices) {
  79018. this.prepare();
  79019. }
  79020. return this._transformMatrices;
  79021. };
  79022. /**
  79023. * Gets the current hosting scene
  79024. * @returns a scene object
  79025. */
  79026. Skeleton.prototype.getScene = function () {
  79027. return this._scene;
  79028. };
  79029. // Methods
  79030. /**
  79031. * Gets a string representing the current skeleton data
  79032. * @param fullDetails defines a boolean indicating if we want a verbose version
  79033. * @returns a string representing the current skeleton data
  79034. */
  79035. Skeleton.prototype.toString = function (fullDetails) {
  79036. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79037. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79038. if (fullDetails) {
  79039. ret += ", Ranges: {";
  79040. var first = true;
  79041. for (var name_1 in this._ranges) {
  79042. if (first) {
  79043. ret += ", ";
  79044. first = false;
  79045. }
  79046. ret += name_1;
  79047. }
  79048. ret += "}";
  79049. }
  79050. return ret;
  79051. };
  79052. /**
  79053. * Get bone's index searching by name
  79054. * @param name defines bone's name to search for
  79055. * @return the indice of the bone. Returns -1 if not found
  79056. */
  79057. Skeleton.prototype.getBoneIndexByName = function (name) {
  79058. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79059. if (this.bones[boneIndex].name === name) {
  79060. return boneIndex;
  79061. }
  79062. }
  79063. return -1;
  79064. };
  79065. /**
  79066. * Creater a new animation range
  79067. * @param name defines the name of the range
  79068. * @param from defines the start key
  79069. * @param to defines the end key
  79070. */
  79071. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79072. // check name not already in use
  79073. if (!this._ranges[name]) {
  79074. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79075. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79076. if (this.bones[i].animations[0]) {
  79077. this.bones[i].animations[0].createRange(name, from, to);
  79078. }
  79079. }
  79080. }
  79081. };
  79082. /**
  79083. * Delete a specific animation range
  79084. * @param name defines the name of the range
  79085. * @param deleteFrames defines if frames must be removed as well
  79086. */
  79087. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79088. if (deleteFrames === void 0) { deleteFrames = true; }
  79089. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79090. if (this.bones[i].animations[0]) {
  79091. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79092. }
  79093. }
  79094. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79095. };
  79096. /**
  79097. * Gets a specific animation range
  79098. * @param name defines the name of the range to look for
  79099. * @returns the requested animation range or null if not found
  79100. */
  79101. Skeleton.prototype.getAnimationRange = function (name) {
  79102. return this._ranges[name];
  79103. };
  79104. /**
  79105. * Gets the list of all animation ranges defined on this skeleton
  79106. * @returns an array
  79107. */
  79108. Skeleton.prototype.getAnimationRanges = function () {
  79109. var animationRanges = [];
  79110. var name;
  79111. var i = 0;
  79112. for (name in this._ranges) {
  79113. animationRanges[i] = this._ranges[name];
  79114. i++;
  79115. }
  79116. return animationRanges;
  79117. };
  79118. /**
  79119. * Copy animation range from a source skeleton.
  79120. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79121. * @param source defines the source skeleton
  79122. * @param name defines the name of the range to copy
  79123. * @param rescaleAsRequired defines if rescaling must be applied if required
  79124. * @returns true if operation was successful
  79125. */
  79126. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79127. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79128. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79129. return false;
  79130. }
  79131. var ret = true;
  79132. var frameOffset = this._getHighestAnimationFrame() + 1;
  79133. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79134. var boneDict = {};
  79135. var sourceBones = source.bones;
  79136. var nBones;
  79137. var i;
  79138. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79139. boneDict[sourceBones[i].name] = sourceBones[i];
  79140. }
  79141. if (this.bones.length !== sourceBones.length) {
  79142. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79143. ret = false;
  79144. }
  79145. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79146. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79147. var boneName = this.bones[i].name;
  79148. var sourceBone = boneDict[boneName];
  79149. if (sourceBone) {
  79150. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79151. }
  79152. else {
  79153. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79154. ret = false;
  79155. }
  79156. }
  79157. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79158. var range = source.getAnimationRange(name);
  79159. if (range) {
  79160. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79161. }
  79162. return ret;
  79163. };
  79164. /**
  79165. * Forces the skeleton to go to rest pose
  79166. */
  79167. Skeleton.prototype.returnToRest = function () {
  79168. for (var index = 0; index < this.bones.length; index++) {
  79169. this.bones[index].returnToRest();
  79170. }
  79171. };
  79172. Skeleton.prototype._getHighestAnimationFrame = function () {
  79173. var ret = 0;
  79174. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79175. if (this.bones[i].animations[0]) {
  79176. var highest = this.bones[i].animations[0].getHighestFrame();
  79177. if (ret < highest) {
  79178. ret = highest;
  79179. }
  79180. }
  79181. }
  79182. return ret;
  79183. };
  79184. /**
  79185. * Begin a specific animation range
  79186. * @param name defines the name of the range to start
  79187. * @param loop defines if looping must be turned on (false by default)
  79188. * @param speedRatio defines the speed ratio to apply (1 by default)
  79189. * @param onAnimationEnd defines a callback which will be called when animation will end
  79190. * @returns a new animatable
  79191. */
  79192. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79193. var range = this.getAnimationRange(name);
  79194. if (!range) {
  79195. return null;
  79196. }
  79197. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79198. };
  79199. /** @hidden */
  79200. Skeleton.prototype._markAsDirty = function () {
  79201. this._isDirty = true;
  79202. };
  79203. /** @hidden */
  79204. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79205. this._meshesWithPoseMatrix.push(mesh);
  79206. };
  79207. /** @hidden */
  79208. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79209. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79210. if (index > -1) {
  79211. this._meshesWithPoseMatrix.splice(index, 1);
  79212. }
  79213. };
  79214. /** @hidden */
  79215. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79216. this.onBeforeComputeObservable.notifyObservers(this);
  79217. for (var index = 0; index < this.bones.length; index++) {
  79218. var bone = this.bones[index];
  79219. var parentBone = bone.getParent();
  79220. if (parentBone) {
  79221. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79222. }
  79223. else {
  79224. if (initialSkinMatrix) {
  79225. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79226. }
  79227. else {
  79228. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79229. }
  79230. }
  79231. if (bone._index !== -1) {
  79232. var mappedIndex = bone._index === null ? index : bone._index;
  79233. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79234. }
  79235. }
  79236. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79237. };
  79238. /**
  79239. * Build all resources required to render a skeleton
  79240. */
  79241. Skeleton.prototype.prepare = function () {
  79242. if (!this._isDirty) {
  79243. return;
  79244. }
  79245. if (this.needInitialSkinMatrix) {
  79246. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79247. var mesh = this._meshesWithPoseMatrix[index];
  79248. var poseMatrix = mesh.getPoseMatrix();
  79249. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79250. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79251. }
  79252. if (this._synchronizedWithMesh !== mesh) {
  79253. this._synchronizedWithMesh = mesh;
  79254. // Prepare bones
  79255. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79256. var bone = this.bones[boneIndex];
  79257. if (!bone.getParent()) {
  79258. var matrix = bone.getBaseMatrix();
  79259. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79260. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79261. }
  79262. }
  79263. }
  79264. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79265. }
  79266. }
  79267. else {
  79268. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79269. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79270. }
  79271. this._computeTransformMatrices(this._transformMatrices, null);
  79272. }
  79273. this._isDirty = false;
  79274. this._scene._activeBones.addCount(this.bones.length, false);
  79275. };
  79276. /**
  79277. * Gets the list of animatables currently running for this skeleton
  79278. * @returns an array of animatables
  79279. */
  79280. Skeleton.prototype.getAnimatables = function () {
  79281. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79282. this._animatables = [];
  79283. for (var index = 0; index < this.bones.length; index++) {
  79284. this._animatables.push(this.bones[index]);
  79285. }
  79286. }
  79287. return this._animatables;
  79288. };
  79289. /**
  79290. * Clone the current skeleton
  79291. * @param name defines the name of the new skeleton
  79292. * @param id defines the id of the enw skeleton
  79293. * @returns the new skeleton
  79294. */
  79295. Skeleton.prototype.clone = function (name, id) {
  79296. var result = new Skeleton(name, id || name, this._scene);
  79297. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79298. for (var index = 0; index < this.bones.length; index++) {
  79299. var source = this.bones[index];
  79300. var parentBone = null;
  79301. var parent_1 = source.getParent();
  79302. if (parent_1) {
  79303. var parentIndex = this.bones.indexOf(parent_1);
  79304. parentBone = result.bones[parentIndex];
  79305. }
  79306. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79307. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79308. }
  79309. if (this._ranges) {
  79310. result._ranges = {};
  79311. for (var rangeName in this._ranges) {
  79312. var range = this._ranges[rangeName];
  79313. if (range) {
  79314. result._ranges[rangeName] = range.clone();
  79315. }
  79316. }
  79317. }
  79318. this._isDirty = true;
  79319. return result;
  79320. };
  79321. /**
  79322. * Enable animation blending for this skeleton
  79323. * @param blendingSpeed defines the blending speed to apply
  79324. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79325. */
  79326. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79327. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79328. this.bones.forEach(function (bone) {
  79329. bone.animations.forEach(function (animation) {
  79330. animation.enableBlending = true;
  79331. animation.blendingSpeed = blendingSpeed;
  79332. });
  79333. });
  79334. };
  79335. /**
  79336. * Releases all resources associated with the current skeleton
  79337. */
  79338. Skeleton.prototype.dispose = function () {
  79339. this._meshesWithPoseMatrix = [];
  79340. // Animations
  79341. this.getScene().stopAnimation(this);
  79342. // Remove from scene
  79343. this.getScene().removeSkeleton(this);
  79344. };
  79345. /**
  79346. * Serialize the skeleton in a JSON object
  79347. * @returns a JSON object
  79348. */
  79349. Skeleton.prototype.serialize = function () {
  79350. var serializationObject = {};
  79351. serializationObject.name = this.name;
  79352. serializationObject.id = this.id;
  79353. if (this.dimensionsAtRest) {
  79354. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79355. }
  79356. serializationObject.bones = [];
  79357. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79358. for (var index = 0; index < this.bones.length; index++) {
  79359. var bone = this.bones[index];
  79360. var parent_2 = bone.getParent();
  79361. var serializedBone = {
  79362. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79363. name: bone.name,
  79364. matrix: bone.getBaseMatrix().toArray(),
  79365. rest: bone.getRestPose().toArray()
  79366. };
  79367. serializationObject.bones.push(serializedBone);
  79368. if (bone.length) {
  79369. serializedBone.length = bone.length;
  79370. }
  79371. if (bone.animations && bone.animations.length > 0) {
  79372. serializedBone.animation = bone.animations[0].serialize();
  79373. }
  79374. serializationObject.ranges = [];
  79375. for (var name in this._ranges) {
  79376. var source = this._ranges[name];
  79377. if (!source) {
  79378. continue;
  79379. }
  79380. var range = {};
  79381. range.name = name;
  79382. range.from = source.from;
  79383. range.to = source.to;
  79384. serializationObject.ranges.push(range);
  79385. }
  79386. }
  79387. return serializationObject;
  79388. };
  79389. /**
  79390. * Creates a new skeleton from serialized data
  79391. * @param parsedSkeleton defines the serialized data
  79392. * @param scene defines the hosting scene
  79393. * @returns a new skeleton
  79394. */
  79395. Skeleton.Parse = function (parsedSkeleton, scene) {
  79396. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79397. if (parsedSkeleton.dimensionsAtRest) {
  79398. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79399. }
  79400. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79401. var index;
  79402. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79403. var parsedBone = parsedSkeleton.bones[index];
  79404. var parentBone = null;
  79405. if (parsedBone.parentBoneIndex > -1) {
  79406. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79407. }
  79408. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79409. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79410. if (parsedBone.length) {
  79411. bone.length = parsedBone.length;
  79412. }
  79413. if (parsedBone.animation) {
  79414. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79415. }
  79416. }
  79417. // placed after bones, so createAnimationRange can cascade down
  79418. if (parsedSkeleton.ranges) {
  79419. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79420. var data = parsedSkeleton.ranges[index];
  79421. skeleton.createAnimationRange(data.name, data.from, data.to);
  79422. }
  79423. }
  79424. return skeleton;
  79425. };
  79426. /**
  79427. * Compute all node absolute transforms
  79428. * @param forceUpdate defines if computation must be done even if cache is up to date
  79429. */
  79430. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79431. if (forceUpdate === void 0) { forceUpdate = false; }
  79432. var renderId = this._scene.getRenderId();
  79433. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79434. this.bones[0].computeAbsoluteTransforms();
  79435. this._lastAbsoluteTransformsUpdateId = renderId;
  79436. }
  79437. };
  79438. /**
  79439. * Gets the root pose matrix
  79440. * @returns a matrix
  79441. */
  79442. Skeleton.prototype.getPoseMatrix = function () {
  79443. var poseMatrix = null;
  79444. if (this._meshesWithPoseMatrix.length > 0) {
  79445. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79446. }
  79447. return poseMatrix;
  79448. };
  79449. /**
  79450. * Sorts bones per internal index
  79451. */
  79452. Skeleton.prototype.sortBones = function () {
  79453. var bones = new Array();
  79454. var visited = new Array(this.bones.length);
  79455. for (var index = 0; index < this.bones.length; index++) {
  79456. this._sortBones(index, bones, visited);
  79457. }
  79458. this.bones = bones;
  79459. };
  79460. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79461. if (visited[index]) {
  79462. return;
  79463. }
  79464. visited[index] = true;
  79465. var bone = this.bones[index];
  79466. if (bone._index === undefined) {
  79467. bone._index = index;
  79468. }
  79469. var parentBone = bone.getParent();
  79470. if (parentBone) {
  79471. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79472. }
  79473. bones.push(bone);
  79474. };
  79475. return Skeleton;
  79476. }());
  79477. BABYLON.Skeleton = Skeleton;
  79478. })(BABYLON || (BABYLON = {}));
  79479. //# sourceMappingURL=babylon.skeleton.js.map
  79480. var BABYLON;
  79481. (function (BABYLON) {
  79482. var SphericalPolynomial = /** @class */ (function () {
  79483. function SphericalPolynomial() {
  79484. this.x = BABYLON.Vector3.Zero();
  79485. this.y = BABYLON.Vector3.Zero();
  79486. this.z = BABYLON.Vector3.Zero();
  79487. this.xx = BABYLON.Vector3.Zero();
  79488. this.yy = BABYLON.Vector3.Zero();
  79489. this.zz = BABYLON.Vector3.Zero();
  79490. this.xy = BABYLON.Vector3.Zero();
  79491. this.yz = BABYLON.Vector3.Zero();
  79492. this.zx = BABYLON.Vector3.Zero();
  79493. }
  79494. SphericalPolynomial.prototype.addAmbient = function (color) {
  79495. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79496. this.xx = this.xx.add(colorVector);
  79497. this.yy = this.yy.add(colorVector);
  79498. this.zz = this.zz.add(colorVector);
  79499. };
  79500. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79501. var result = new SphericalPolynomial();
  79502. result.x = harmonics.L11.scale(1.02333);
  79503. result.y = harmonics.L1_1.scale(1.02333);
  79504. result.z = harmonics.L10.scale(1.02333);
  79505. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79506. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79507. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79508. result.yz = harmonics.L2_1.scale(0.858086);
  79509. result.zx = harmonics.L21.scale(0.858086);
  79510. result.xy = harmonics.L2_2.scale(0.858086);
  79511. result.scale(1.0 / Math.PI);
  79512. return result;
  79513. };
  79514. SphericalPolynomial.prototype.scale = function (scale) {
  79515. this.x = this.x.scale(scale);
  79516. this.y = this.y.scale(scale);
  79517. this.z = this.z.scale(scale);
  79518. this.xx = this.xx.scale(scale);
  79519. this.yy = this.yy.scale(scale);
  79520. this.zz = this.zz.scale(scale);
  79521. this.yz = this.yz.scale(scale);
  79522. this.zx = this.zx.scale(scale);
  79523. this.xy = this.xy.scale(scale);
  79524. };
  79525. return SphericalPolynomial;
  79526. }());
  79527. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79528. var SphericalHarmonics = /** @class */ (function () {
  79529. function SphericalHarmonics() {
  79530. this.L00 = BABYLON.Vector3.Zero();
  79531. this.L1_1 = BABYLON.Vector3.Zero();
  79532. this.L10 = BABYLON.Vector3.Zero();
  79533. this.L11 = BABYLON.Vector3.Zero();
  79534. this.L2_2 = BABYLON.Vector3.Zero();
  79535. this.L2_1 = BABYLON.Vector3.Zero();
  79536. this.L20 = BABYLON.Vector3.Zero();
  79537. this.L21 = BABYLON.Vector3.Zero();
  79538. this.L22 = BABYLON.Vector3.Zero();
  79539. }
  79540. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79541. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79542. var c = colorVector.scale(deltaSolidAngle);
  79543. this.L00 = this.L00.add(c.scale(0.282095));
  79544. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79545. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79546. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79547. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79548. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79549. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79550. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79551. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79552. };
  79553. SphericalHarmonics.prototype.scale = function (scale) {
  79554. this.L00 = this.L00.scale(scale);
  79555. this.L1_1 = this.L1_1.scale(scale);
  79556. this.L10 = this.L10.scale(scale);
  79557. this.L11 = this.L11.scale(scale);
  79558. this.L2_2 = this.L2_2.scale(scale);
  79559. this.L2_1 = this.L2_1.scale(scale);
  79560. this.L20 = this.L20.scale(scale);
  79561. this.L21 = this.L21.scale(scale);
  79562. this.L22 = this.L22.scale(scale);
  79563. };
  79564. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79565. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79566. //
  79567. // E_lm = A_l * L_lm
  79568. //
  79569. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79570. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79571. // the scaling factors are given in equation 9.
  79572. // Constant (Band 0)
  79573. this.L00 = this.L00.scale(3.141593);
  79574. // Linear (Band 1)
  79575. this.L1_1 = this.L1_1.scale(2.094395);
  79576. this.L10 = this.L10.scale(2.094395);
  79577. this.L11 = this.L11.scale(2.094395);
  79578. // Quadratic (Band 2)
  79579. this.L2_2 = this.L2_2.scale(0.785398);
  79580. this.L2_1 = this.L2_1.scale(0.785398);
  79581. this.L20 = this.L20.scale(0.785398);
  79582. this.L21 = this.L21.scale(0.785398);
  79583. this.L22 = this.L22.scale(0.785398);
  79584. };
  79585. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79586. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79587. // L = (1/pi) * E * rho
  79588. //
  79589. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79590. this.scale(1.0 / Math.PI);
  79591. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79592. // (The pixel shader must apply albedo after texture fetches, etc).
  79593. };
  79594. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79595. var result = new SphericalHarmonics();
  79596. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79597. result.L1_1 = polynomial.y.scale(0.977204);
  79598. result.L10 = polynomial.z.scale(0.977204);
  79599. result.L11 = polynomial.x.scale(0.977204);
  79600. result.L2_2 = polynomial.xy.scale(1.16538);
  79601. result.L2_1 = polynomial.yz.scale(1.16538);
  79602. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79603. result.L21 = polynomial.zx.scale(1.16538);
  79604. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79605. result.scale(Math.PI);
  79606. return result;
  79607. };
  79608. return SphericalHarmonics;
  79609. }());
  79610. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79611. })(BABYLON || (BABYLON = {}));
  79612. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79613. var BABYLON;
  79614. (function (BABYLON) {
  79615. var FileFaceOrientation = /** @class */ (function () {
  79616. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79617. this.name = name;
  79618. this.worldAxisForNormal = worldAxisForNormal;
  79619. this.worldAxisForFileX = worldAxisForFileX;
  79620. this.worldAxisForFileY = worldAxisForFileY;
  79621. }
  79622. return FileFaceOrientation;
  79623. }());
  79624. ;
  79625. /**
  79626. * Helper class dealing with the extraction of spherical polynomial dataArray
  79627. * from a cube map.
  79628. */
  79629. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79630. function CubeMapToSphericalPolynomialTools() {
  79631. }
  79632. /**
  79633. * Converts a texture to the according Spherical Polynomial data.
  79634. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79635. *
  79636. * @param texture The texture to extract the information from.
  79637. * @return The Spherical Polynomial data.
  79638. */
  79639. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79640. if (!texture.isCube) {
  79641. // Only supports cube Textures currently.
  79642. return null;
  79643. }
  79644. var size = texture.getSize().width;
  79645. var right = texture.readPixels(0);
  79646. var left = texture.readPixels(1);
  79647. var up;
  79648. var down;
  79649. if (texture.isRenderTarget) {
  79650. up = texture.readPixels(3);
  79651. down = texture.readPixels(2);
  79652. }
  79653. else {
  79654. up = texture.readPixels(2);
  79655. down = texture.readPixels(3);
  79656. }
  79657. var front = texture.readPixels(4);
  79658. var back = texture.readPixels(5);
  79659. var gammaSpace = texture.gammaSpace;
  79660. // Always read as RGBA.
  79661. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79662. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79663. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79664. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79665. }
  79666. var cubeInfo = {
  79667. size: size,
  79668. right: right,
  79669. left: left,
  79670. up: up,
  79671. down: down,
  79672. front: front,
  79673. back: back,
  79674. format: format,
  79675. type: type,
  79676. gammaSpace: gammaSpace,
  79677. };
  79678. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79679. };
  79680. /**
  79681. * Converts a cubemap to the according Spherical Polynomial data.
  79682. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79683. *
  79684. * @param cubeInfo The Cube map to extract the information from.
  79685. * @return The Spherical Polynomial data.
  79686. */
  79687. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79688. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79689. var totalSolidAngle = 0.0;
  79690. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79691. var du = 2.0 / cubeInfo.size;
  79692. var dv = du;
  79693. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79694. var minUV = du * 0.5 - 1.0;
  79695. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79696. var fileFace = this.FileFaces[faceIndex];
  79697. var dataArray = cubeInfo[fileFace.name];
  79698. var v = minUV;
  79699. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79700. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79701. // Because SP is still linear, so summation is fine in that basis.
  79702. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79703. for (var y = 0; y < cubeInfo.size; y++) {
  79704. var u = minUV;
  79705. for (var x = 0; x < cubeInfo.size; x++) {
  79706. // World direction (not normalised)
  79707. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79708. worldDirection.normalize();
  79709. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79710. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79711. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79712. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79713. // Handle Integer types.
  79714. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79715. r /= 255;
  79716. g /= 255;
  79717. b /= 255;
  79718. }
  79719. // Handle Gamma space textures.
  79720. if (cubeInfo.gammaSpace) {
  79721. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79722. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79723. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79724. }
  79725. var color = new BABYLON.Color3(r, g, b);
  79726. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79727. totalSolidAngle += deltaSolidAngle;
  79728. u += du;
  79729. }
  79730. v += dv;
  79731. }
  79732. }
  79733. // Solid angle for entire sphere is 4*pi
  79734. var sphereSolidAngle = 4.0 * Math.PI;
  79735. // Adjust the solid angle to allow for how many faces we processed.
  79736. var facesProcessed = 6.0;
  79737. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79738. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79739. // This is needed because the numerical integration over the cube uses a
  79740. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79741. // and also to compensate for accumulative error due to float precision in the summation.
  79742. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79743. sphericalHarmonics.scale(correctionFactor);
  79744. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79745. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79746. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79747. };
  79748. CubeMapToSphericalPolynomialTools.FileFaces = [
  79749. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79750. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79751. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79752. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79753. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79754. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79755. ];
  79756. return CubeMapToSphericalPolynomialTools;
  79757. }());
  79758. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79759. })(BABYLON || (BABYLON = {}));
  79760. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79761. var BABYLON;
  79762. (function (BABYLON) {
  79763. /**
  79764. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79765. */
  79766. var PanoramaToCubeMapTools = /** @class */ (function () {
  79767. function PanoramaToCubeMapTools() {
  79768. }
  79769. /**
  79770. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79771. *
  79772. * @param float32Array The source data.
  79773. * @param inputWidth The width of the input panorama.
  79774. * @param inputhHeight The height of the input panorama.
  79775. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79776. * @return The cubemap data
  79777. */
  79778. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79779. if (!float32Array) {
  79780. throw "ConvertPanoramaToCubemap: input cannot be null";
  79781. }
  79782. if (float32Array.length != inputWidth * inputHeight * 3) {
  79783. throw "ConvertPanoramaToCubemap: input size is wrong";
  79784. }
  79785. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79786. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79787. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79788. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79789. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79790. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79791. return {
  79792. front: textureFront,
  79793. back: textureBack,
  79794. left: textureLeft,
  79795. right: textureRight,
  79796. up: textureUp,
  79797. down: textureDown,
  79798. size: size,
  79799. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79800. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79801. gammaSpace: false,
  79802. };
  79803. };
  79804. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79805. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79806. var textureArray = new Float32Array(buffer);
  79807. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79808. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79809. var dy = 1 / texSize;
  79810. var fy = 0;
  79811. for (var y = 0; y < texSize; y++) {
  79812. var xv1 = faceData[0];
  79813. var xv2 = faceData[2];
  79814. for (var x = 0; x < texSize; x++) {
  79815. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79816. v.normalize();
  79817. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79818. // 3 channels per pixels
  79819. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79820. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79821. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79822. xv1 = xv1.add(rotDX1);
  79823. xv2 = xv2.add(rotDX2);
  79824. }
  79825. fy += dy;
  79826. }
  79827. return textureArray;
  79828. };
  79829. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79830. var theta = Math.atan2(vDir.z, vDir.x);
  79831. var phi = Math.acos(vDir.y);
  79832. while (theta < -Math.PI)
  79833. theta += 2 * Math.PI;
  79834. while (theta > Math.PI)
  79835. theta -= 2 * Math.PI;
  79836. var dx = theta / Math.PI;
  79837. var dy = phi / Math.PI;
  79838. // recenter.
  79839. dx = dx * 0.5 + 0.5;
  79840. var px = Math.round(dx * inputWidth);
  79841. if (px < 0)
  79842. px = 0;
  79843. else if (px >= inputWidth)
  79844. px = inputWidth - 1;
  79845. var py = Math.round(dy * inputHeight);
  79846. if (py < 0)
  79847. py = 0;
  79848. else if (py >= inputHeight)
  79849. py = inputHeight - 1;
  79850. var inputY = (inputHeight - py - 1);
  79851. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79852. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79853. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79854. return {
  79855. r: r,
  79856. g: g,
  79857. b: b
  79858. };
  79859. };
  79860. PanoramaToCubeMapTools.FACE_FRONT = [
  79861. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79862. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79863. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79864. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79865. ];
  79866. PanoramaToCubeMapTools.FACE_BACK = [
  79867. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79868. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79869. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79870. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79871. ];
  79872. PanoramaToCubeMapTools.FACE_RIGHT = [
  79873. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79874. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79875. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79876. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79877. ];
  79878. PanoramaToCubeMapTools.FACE_LEFT = [
  79879. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79880. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79881. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79882. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79883. ];
  79884. PanoramaToCubeMapTools.FACE_DOWN = [
  79885. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79886. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79887. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79888. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79889. ];
  79890. PanoramaToCubeMapTools.FACE_UP = [
  79891. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79892. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79893. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79894. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79895. ];
  79896. return PanoramaToCubeMapTools;
  79897. }());
  79898. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79899. })(BABYLON || (BABYLON = {}));
  79900. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79901. var BABYLON;
  79902. (function (BABYLON) {
  79903. ;
  79904. /**
  79905. * This groups tools to convert HDR texture to native colors array.
  79906. */
  79907. var HDRTools = /** @class */ (function () {
  79908. function HDRTools() {
  79909. }
  79910. HDRTools.Ldexp = function (mantissa, exponent) {
  79911. if (exponent > 1023) {
  79912. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79913. }
  79914. if (exponent < -1074) {
  79915. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79916. }
  79917. return mantissa * Math.pow(2, exponent);
  79918. };
  79919. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79920. if (exponent > 0) { /*nonzero pixel*/
  79921. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79922. float32array[index + 0] = red * exponent;
  79923. float32array[index + 1] = green * exponent;
  79924. float32array[index + 2] = blue * exponent;
  79925. }
  79926. else {
  79927. float32array[index + 0] = 0;
  79928. float32array[index + 1] = 0;
  79929. float32array[index + 2] = 0;
  79930. }
  79931. };
  79932. HDRTools.readStringLine = function (uint8array, startIndex) {
  79933. var line = "";
  79934. var character = "";
  79935. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79936. character = String.fromCharCode(uint8array[i]);
  79937. if (character == "\n") {
  79938. break;
  79939. }
  79940. line += character;
  79941. }
  79942. return line;
  79943. };
  79944. /**
  79945. * Reads header information from an RGBE texture stored in a native array.
  79946. * More information on this format are available here:
  79947. * https://en.wikipedia.org/wiki/RGBE_image_format
  79948. *
  79949. * @param uint8array The binary file stored in native array.
  79950. * @return The header information.
  79951. */
  79952. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79953. var height = 0;
  79954. var width = 0;
  79955. var line = this.readStringLine(uint8array, 0);
  79956. if (line[0] != '#' || line[1] != '?') {
  79957. throw "Bad HDR Format.";
  79958. }
  79959. var endOfHeader = false;
  79960. var findFormat = false;
  79961. var lineIndex = 0;
  79962. do {
  79963. lineIndex += (line.length + 1);
  79964. line = this.readStringLine(uint8array, lineIndex);
  79965. if (line == "FORMAT=32-bit_rle_rgbe") {
  79966. findFormat = true;
  79967. }
  79968. else if (line.length == 0) {
  79969. endOfHeader = true;
  79970. }
  79971. } while (!endOfHeader);
  79972. if (!findFormat) {
  79973. throw "HDR Bad header format, unsupported FORMAT";
  79974. }
  79975. lineIndex += (line.length + 1);
  79976. line = this.readStringLine(uint8array, lineIndex);
  79977. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79978. var match = sizeRegexp.exec(line);
  79979. // TODO. Support +Y and -X if needed.
  79980. if (!match || match.length < 3) {
  79981. throw "HDR Bad header format, no size";
  79982. }
  79983. width = parseInt(match[2]);
  79984. height = parseInt(match[1]);
  79985. if (width < 8 || width > 0x7fff) {
  79986. throw "HDR Bad header format, unsupported size";
  79987. }
  79988. lineIndex += (line.length + 1);
  79989. return {
  79990. height: height,
  79991. width: width,
  79992. dataPosition: lineIndex
  79993. };
  79994. };
  79995. /**
  79996. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79997. * This RGBE texture needs to store the information as a panorama.
  79998. *
  79999. * More information on this format are available here:
  80000. * https://en.wikipedia.org/wiki/RGBE_image_format
  80001. *
  80002. * @param buffer The binary file stored in an array buffer.
  80003. * @param size The expected size of the extracted cubemap.
  80004. * @return The Cube Map information.
  80005. */
  80006. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80007. var uint8array = new Uint8Array(buffer);
  80008. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80009. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80010. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80011. return cubeMapData;
  80012. };
  80013. /**
  80014. * Returns the pixels data extracted from an RGBE texture.
  80015. * This pixels will be stored left to right up to down in the R G B order in one array.
  80016. *
  80017. * More information on this format are available here:
  80018. * https://en.wikipedia.org/wiki/RGBE_image_format
  80019. *
  80020. * @param uint8array The binary file stored in an array buffer.
  80021. * @param hdrInfo The header information of the file.
  80022. * @return The pixels data in RGB right to left up to down order.
  80023. */
  80024. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80025. // Keep for multi format supports.
  80026. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80027. };
  80028. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80029. var num_scanlines = hdrInfo.height;
  80030. var scanline_width = hdrInfo.width;
  80031. var a, b, c, d, count;
  80032. var dataIndex = hdrInfo.dataPosition;
  80033. var index = 0, endIndex = 0, i = 0;
  80034. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80035. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80036. // 3 channels of 4 bytes per pixel in float.
  80037. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80038. var resultArray = new Float32Array(resultBuffer);
  80039. // read in each successive scanline
  80040. while (num_scanlines > 0) {
  80041. a = uint8array[dataIndex++];
  80042. b = uint8array[dataIndex++];
  80043. c = uint8array[dataIndex++];
  80044. d = uint8array[dataIndex++];
  80045. if (a != 2 || b != 2 || (c & 0x80)) {
  80046. // this file is not run length encoded
  80047. throw "HDR Bad header format, not RLE";
  80048. }
  80049. if (((c << 8) | d) != scanline_width) {
  80050. throw "HDR Bad header format, wrong scan line width";
  80051. }
  80052. index = 0;
  80053. // read each of the four channels for the scanline into the buffer
  80054. for (i = 0; i < 4; i++) {
  80055. endIndex = (i + 1) * scanline_width;
  80056. while (index < endIndex) {
  80057. a = uint8array[dataIndex++];
  80058. b = uint8array[dataIndex++];
  80059. if (a > 128) {
  80060. // a run of the same value
  80061. count = a - 128;
  80062. if ((count == 0) || (count > endIndex - index)) {
  80063. throw "HDR Bad Format, bad scanline data (run)";
  80064. }
  80065. while (count-- > 0) {
  80066. scanLineArray[index++] = b;
  80067. }
  80068. }
  80069. else {
  80070. // a non-run
  80071. count = a;
  80072. if ((count == 0) || (count > endIndex - index)) {
  80073. throw "HDR Bad Format, bad scanline data (non-run)";
  80074. }
  80075. scanLineArray[index++] = b;
  80076. if (--count > 0) {
  80077. for (var j = 0; j < count; j++) {
  80078. scanLineArray[index++] = uint8array[dataIndex++];
  80079. }
  80080. }
  80081. }
  80082. }
  80083. }
  80084. // now convert data from buffer into floats
  80085. for (i = 0; i < scanline_width; i++) {
  80086. a = scanLineArray[i];
  80087. b = scanLineArray[i + scanline_width];
  80088. c = scanLineArray[i + 2 * scanline_width];
  80089. d = scanLineArray[i + 3 * scanline_width];
  80090. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80091. }
  80092. num_scanlines--;
  80093. }
  80094. return resultArray;
  80095. };
  80096. return HDRTools;
  80097. }());
  80098. BABYLON.HDRTools = HDRTools;
  80099. })(BABYLON || (BABYLON = {}));
  80100. //# sourceMappingURL=babylon.hdr.js.map
  80101. var BABYLON;
  80102. (function (BABYLON) {
  80103. /**
  80104. * This represents a texture coming from an HDR input.
  80105. *
  80106. * The only supported format is currently panorama picture stored in RGBE format.
  80107. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80108. */
  80109. var HDRCubeTexture = /** @class */ (function (_super) {
  80110. __extends(HDRCubeTexture, _super);
  80111. /**
  80112. * Instantiates an HDRTexture from the following parameters.
  80113. *
  80114. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80115. * @param scene The scene the texture will be used in
  80116. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80117. * @param noMipmap Forces to not generate the mipmap if true
  80118. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80119. * @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)
  80120. * @param reserved Reserved flag for internal use.
  80121. */
  80122. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80123. if (noMipmap === void 0) { noMipmap = false; }
  80124. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80125. if (gammaSpace === void 0) { gammaSpace = false; }
  80126. if (reserved === void 0) { reserved = false; }
  80127. if (onLoad === void 0) { onLoad = null; }
  80128. if (onError === void 0) { onError = null; }
  80129. var _this = _super.call(this, scene) || this;
  80130. _this._generateHarmonics = true;
  80131. _this._onLoad = null;
  80132. _this._onError = null;
  80133. /**
  80134. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80135. */
  80136. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80137. _this._isBlocking = true;
  80138. _this._rotationY = 0;
  80139. /**
  80140. * Gets or sets the center of the bounding box associated with the cube texture
  80141. * It must define where the camera used to render the texture was set
  80142. */
  80143. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80144. if (!url) {
  80145. return _this;
  80146. }
  80147. _this.name = url;
  80148. _this.url = url;
  80149. _this.hasAlpha = false;
  80150. _this.isCube = true;
  80151. _this._textureMatrix = BABYLON.Matrix.Identity();
  80152. _this._onLoad = onLoad;
  80153. _this._onError = onError;
  80154. _this.gammaSpace = gammaSpace;
  80155. _this._noMipmap = noMipmap;
  80156. _this._size = size;
  80157. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80158. if (!_this._texture) {
  80159. if (!scene.useDelayedTextureLoading) {
  80160. _this.loadTexture();
  80161. }
  80162. else {
  80163. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80164. }
  80165. }
  80166. return _this;
  80167. }
  80168. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80169. /**
  80170. * Gets wether or not the texture is blocking during loading.
  80171. */
  80172. get: function () {
  80173. return this._isBlocking;
  80174. },
  80175. /**
  80176. * Sets wether or not the texture is blocking during loading.
  80177. */
  80178. set: function (value) {
  80179. this._isBlocking = value;
  80180. },
  80181. enumerable: true,
  80182. configurable: true
  80183. });
  80184. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80185. /**
  80186. * Gets texture matrix rotation angle around Y axis radians.
  80187. */
  80188. get: function () {
  80189. return this._rotationY;
  80190. },
  80191. /**
  80192. * Sets texture matrix rotation angle around Y axis in radians.
  80193. */
  80194. set: function (value) {
  80195. this._rotationY = value;
  80196. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80197. },
  80198. enumerable: true,
  80199. configurable: true
  80200. });
  80201. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80202. get: function () {
  80203. return this._boundingBoxSize;
  80204. },
  80205. /**
  80206. * Gets or sets the size of the bounding box associated with the cube texture
  80207. * When defined, the cubemap will switch to local mode
  80208. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80209. * @example https://www.babylonjs-playground.com/#RNASML
  80210. */
  80211. set: function (value) {
  80212. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80213. return;
  80214. }
  80215. this._boundingBoxSize = value;
  80216. var scene = this.getScene();
  80217. if (scene) {
  80218. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80219. }
  80220. },
  80221. enumerable: true,
  80222. configurable: true
  80223. });
  80224. /**
  80225. * Occurs when the file is raw .hdr file.
  80226. */
  80227. HDRCubeTexture.prototype.loadTexture = function () {
  80228. var _this = this;
  80229. var callback = function (buffer) {
  80230. var scene = _this.getScene();
  80231. if (!scene) {
  80232. return null;
  80233. }
  80234. // Extract the raw linear data.
  80235. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80236. // Generate harmonics if needed.
  80237. if (_this._generateHarmonics) {
  80238. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80239. _this.sphericalPolynomial = sphericalPolynomial;
  80240. }
  80241. var results = [];
  80242. var byteArray = null;
  80243. // Push each faces.
  80244. for (var j = 0; j < 6; j++) {
  80245. // Create uintarray fallback.
  80246. if (!scene.getEngine().getCaps().textureFloat) {
  80247. // 3 channels of 1 bytes per pixel in bytes.
  80248. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80249. byteArray = new Uint8Array(byteBuffer);
  80250. }
  80251. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80252. // If special cases.
  80253. if (_this.gammaSpace || byteArray) {
  80254. for (var i = 0; i < _this._size * _this._size; i++) {
  80255. // Put in gamma space if requested.
  80256. if (_this.gammaSpace) {
  80257. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80258. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80259. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80260. }
  80261. // Convert to int texture for fallback.
  80262. if (byteArray) {
  80263. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80264. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80265. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80266. // May use luminance instead if the result is not accurate.
  80267. var max = Math.max(Math.max(r, g), b);
  80268. if (max > 255) {
  80269. var scale = 255 / max;
  80270. r *= scale;
  80271. g *= scale;
  80272. b *= scale;
  80273. }
  80274. byteArray[(i * 3) + 0] = r;
  80275. byteArray[(i * 3) + 1] = g;
  80276. byteArray[(i * 3) + 2] = b;
  80277. }
  80278. }
  80279. }
  80280. if (byteArray) {
  80281. results.push(byteArray);
  80282. }
  80283. else {
  80284. results.push(dataFace);
  80285. }
  80286. }
  80287. return results;
  80288. };
  80289. var scene = this.getScene();
  80290. if (scene) {
  80291. 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);
  80292. }
  80293. };
  80294. HDRCubeTexture.prototype.clone = function () {
  80295. var scene = this.getScene();
  80296. if (!scene) {
  80297. return this;
  80298. }
  80299. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80300. // Base texture
  80301. newTexture.level = this.level;
  80302. newTexture.wrapU = this.wrapU;
  80303. newTexture.wrapV = this.wrapV;
  80304. newTexture.coordinatesIndex = this.coordinatesIndex;
  80305. newTexture.coordinatesMode = this.coordinatesMode;
  80306. return newTexture;
  80307. };
  80308. // Methods
  80309. HDRCubeTexture.prototype.delayLoad = function () {
  80310. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80311. return;
  80312. }
  80313. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80314. this._texture = this._getFromCache(this.url, this._noMipmap);
  80315. if (!this._texture) {
  80316. this.loadTexture();
  80317. }
  80318. };
  80319. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80320. return this._textureMatrix;
  80321. };
  80322. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80323. this._textureMatrix = value;
  80324. };
  80325. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80326. var texture = null;
  80327. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80328. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80329. texture.name = parsedTexture.name;
  80330. texture.hasAlpha = parsedTexture.hasAlpha;
  80331. texture.level = parsedTexture.level;
  80332. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80333. texture.isBlocking = parsedTexture.isBlocking;
  80334. }
  80335. if (texture) {
  80336. if (parsedTexture.boundingBoxPosition) {
  80337. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80338. }
  80339. if (parsedTexture.boundingBoxSize) {
  80340. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80341. }
  80342. if (parsedTexture.rotationY) {
  80343. texture.rotationY = parsedTexture.rotationY;
  80344. }
  80345. }
  80346. return texture;
  80347. };
  80348. HDRCubeTexture.prototype.serialize = function () {
  80349. if (!this.name) {
  80350. return null;
  80351. }
  80352. var serializationObject = {};
  80353. serializationObject.name = this.name;
  80354. serializationObject.hasAlpha = this.hasAlpha;
  80355. serializationObject.isCube = true;
  80356. serializationObject.level = this.level;
  80357. serializationObject.size = this._size;
  80358. serializationObject.coordinatesMode = this.coordinatesMode;
  80359. serializationObject.useInGammaSpace = this.gammaSpace;
  80360. serializationObject.generateHarmonics = this._generateHarmonics;
  80361. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80362. serializationObject.noMipmap = this._noMipmap;
  80363. serializationObject.isBlocking = this._isBlocking;
  80364. serializationObject.rotationY = this._rotationY;
  80365. return serializationObject;
  80366. };
  80367. HDRCubeTexture._facesMapping = [
  80368. "right",
  80369. "left",
  80370. "up",
  80371. "down",
  80372. "front",
  80373. "back"
  80374. ];
  80375. return HDRCubeTexture;
  80376. }(BABYLON.BaseTexture));
  80377. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80378. })(BABYLON || (BABYLON = {}));
  80379. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80380. var BABYLON;
  80381. (function (BABYLON) {
  80382. var IndexedVector2 = /** @class */ (function (_super) {
  80383. __extends(IndexedVector2, _super);
  80384. function IndexedVector2(original, index) {
  80385. var _this = _super.call(this, original.x, original.y) || this;
  80386. _this.index = index;
  80387. return _this;
  80388. }
  80389. return IndexedVector2;
  80390. }(BABYLON.Vector2));
  80391. var PolygonPoints = /** @class */ (function () {
  80392. function PolygonPoints() {
  80393. this.elements = new Array();
  80394. }
  80395. PolygonPoints.prototype.add = function (originalPoints) {
  80396. var _this = this;
  80397. var result = new Array();
  80398. originalPoints.forEach(function (point) {
  80399. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80400. var newPoint = new IndexedVector2(point, _this.elements.length);
  80401. result.push(newPoint);
  80402. _this.elements.push(newPoint);
  80403. }
  80404. });
  80405. return result;
  80406. };
  80407. PolygonPoints.prototype.computeBounds = function () {
  80408. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80409. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80410. this.elements.forEach(function (point) {
  80411. // x
  80412. if (point.x < lmin.x) {
  80413. lmin.x = point.x;
  80414. }
  80415. else if (point.x > lmax.x) {
  80416. lmax.x = point.x;
  80417. }
  80418. // y
  80419. if (point.y < lmin.y) {
  80420. lmin.y = point.y;
  80421. }
  80422. else if (point.y > lmax.y) {
  80423. lmax.y = point.y;
  80424. }
  80425. });
  80426. return {
  80427. min: lmin,
  80428. max: lmax,
  80429. width: lmax.x - lmin.x,
  80430. height: lmax.y - lmin.y
  80431. };
  80432. };
  80433. return PolygonPoints;
  80434. }());
  80435. var Polygon = /** @class */ (function () {
  80436. function Polygon() {
  80437. }
  80438. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80439. return [
  80440. new BABYLON.Vector2(xmin, ymin),
  80441. new BABYLON.Vector2(xmax, ymin),
  80442. new BABYLON.Vector2(xmax, ymax),
  80443. new BABYLON.Vector2(xmin, ymax)
  80444. ];
  80445. };
  80446. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80447. if (cx === void 0) { cx = 0; }
  80448. if (cy === void 0) { cy = 0; }
  80449. if (numberOfSides === void 0) { numberOfSides = 32; }
  80450. var result = new Array();
  80451. var angle = 0;
  80452. var increment = (Math.PI * 2) / numberOfSides;
  80453. for (var i = 0; i < numberOfSides; i++) {
  80454. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80455. angle -= increment;
  80456. }
  80457. return result;
  80458. };
  80459. Polygon.Parse = function (input) {
  80460. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80461. var i, result = [];
  80462. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80463. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80464. }
  80465. return result;
  80466. };
  80467. Polygon.StartingAt = function (x, y) {
  80468. return BABYLON.Path2.StartingAt(x, y);
  80469. };
  80470. return Polygon;
  80471. }());
  80472. BABYLON.Polygon = Polygon;
  80473. var PolygonMeshBuilder = /** @class */ (function () {
  80474. function PolygonMeshBuilder(name, contours, scene) {
  80475. this._points = new PolygonPoints();
  80476. this._outlinepoints = new PolygonPoints();
  80477. this._holes = new Array();
  80478. this._epoints = new Array();
  80479. this._eholes = new Array();
  80480. this._name = name;
  80481. this._scene = scene;
  80482. var points;
  80483. if (contours instanceof BABYLON.Path2) {
  80484. points = contours.getPoints();
  80485. }
  80486. else {
  80487. points = contours;
  80488. }
  80489. this._addToepoint(points);
  80490. this._points.add(points);
  80491. this._outlinepoints.add(points);
  80492. if (typeof earcut === 'undefined') {
  80493. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80494. }
  80495. }
  80496. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80497. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80498. var p = points_1[_i];
  80499. this._epoints.push(p.x, p.y);
  80500. }
  80501. };
  80502. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80503. this._points.add(hole);
  80504. var holepoints = new PolygonPoints();
  80505. holepoints.add(hole);
  80506. this._holes.push(holepoints);
  80507. this._eholes.push(this._epoints.length / 2);
  80508. this._addToepoint(hole);
  80509. return this;
  80510. };
  80511. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80512. var _this = this;
  80513. if (updatable === void 0) { updatable = false; }
  80514. if (depth === void 0) { depth = 0; }
  80515. var result = new BABYLON.Mesh(this._name, this._scene);
  80516. var normals = new Array();
  80517. var positions = new Array();
  80518. var uvs = new Array();
  80519. var bounds = this._points.computeBounds();
  80520. this._points.elements.forEach(function (p) {
  80521. normals.push(0, 1.0, 0);
  80522. positions.push(p.x, 0, p.y);
  80523. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80524. });
  80525. var indices = new Array();
  80526. var res = earcut(this._epoints, this._eholes, 2);
  80527. for (var i = 0; i < res.length; i++) {
  80528. indices.push(res[i]);
  80529. }
  80530. if (depth > 0) {
  80531. var positionscount = (positions.length / 3); //get the current pointcount
  80532. this._points.elements.forEach(function (p) {
  80533. normals.push(0, -1.0, 0);
  80534. positions.push(p.x, -depth, p.y);
  80535. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80536. });
  80537. var totalCount = indices.length;
  80538. for (var i = 0; i < totalCount; i += 3) {
  80539. var i0 = indices[i + 0];
  80540. var i1 = indices[i + 1];
  80541. var i2 = indices[i + 2];
  80542. indices.push(i2 + positionscount);
  80543. indices.push(i1 + positionscount);
  80544. indices.push(i0 + positionscount);
  80545. }
  80546. //Add the sides
  80547. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80548. this._holes.forEach(function (hole) {
  80549. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80550. });
  80551. }
  80552. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80553. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80554. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80555. result.setIndices(indices);
  80556. return result;
  80557. };
  80558. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80559. var StartIndex = positions.length / 3;
  80560. var ulength = 0;
  80561. for (var i = 0; i < points.elements.length; i++) {
  80562. var p = points.elements[i];
  80563. var p1;
  80564. if ((i + 1) > points.elements.length - 1) {
  80565. p1 = points.elements[0];
  80566. }
  80567. else {
  80568. p1 = points.elements[i + 1];
  80569. }
  80570. positions.push(p.x, 0, p.y);
  80571. positions.push(p.x, -depth, p.y);
  80572. positions.push(p1.x, 0, p1.y);
  80573. positions.push(p1.x, -depth, p1.y);
  80574. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80575. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80576. var v3 = v2.subtract(v1);
  80577. var v4 = new BABYLON.Vector3(0, 1, 0);
  80578. var vn = BABYLON.Vector3.Cross(v3, v4);
  80579. vn = vn.normalize();
  80580. uvs.push(ulength / bounds.width, 0);
  80581. uvs.push(ulength / bounds.width, 1);
  80582. ulength += v3.length();
  80583. uvs.push((ulength / bounds.width), 0);
  80584. uvs.push((ulength / bounds.width), 1);
  80585. if (!flip) {
  80586. normals.push(-vn.x, -vn.y, -vn.z);
  80587. normals.push(-vn.x, -vn.y, -vn.z);
  80588. normals.push(-vn.x, -vn.y, -vn.z);
  80589. normals.push(-vn.x, -vn.y, -vn.z);
  80590. indices.push(StartIndex);
  80591. indices.push(StartIndex + 1);
  80592. indices.push(StartIndex + 2);
  80593. indices.push(StartIndex + 1);
  80594. indices.push(StartIndex + 3);
  80595. indices.push(StartIndex + 2);
  80596. }
  80597. else {
  80598. normals.push(vn.x, vn.y, vn.z);
  80599. normals.push(vn.x, vn.y, vn.z);
  80600. normals.push(vn.x, vn.y, vn.z);
  80601. normals.push(vn.x, vn.y, vn.z);
  80602. indices.push(StartIndex);
  80603. indices.push(StartIndex + 2);
  80604. indices.push(StartIndex + 1);
  80605. indices.push(StartIndex + 1);
  80606. indices.push(StartIndex + 2);
  80607. indices.push(StartIndex + 3);
  80608. }
  80609. StartIndex += 4;
  80610. }
  80611. ;
  80612. };
  80613. return PolygonMeshBuilder;
  80614. }());
  80615. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80616. })(BABYLON || (BABYLON = {}));
  80617. //# sourceMappingURL=babylon.polygonMesh.js.map
  80618. var BABYLON;
  80619. (function (BABYLON) {
  80620. // Unique ID when we import meshes from Babylon to CSG
  80621. var currentCSGMeshId = 0;
  80622. // # class Vertex
  80623. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80624. // one to provide additional features like texture coordinates and vertex
  80625. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80626. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80627. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80628. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80629. // is not used anywhere else.
  80630. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80631. var Vertex = /** @class */ (function () {
  80632. function Vertex(pos, normal, uv) {
  80633. this.pos = pos;
  80634. this.normal = normal;
  80635. this.uv = uv;
  80636. }
  80637. Vertex.prototype.clone = function () {
  80638. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80639. };
  80640. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80641. // orientation of a polygon is flipped.
  80642. Vertex.prototype.flip = function () {
  80643. this.normal = this.normal.scale(-1);
  80644. };
  80645. // Create a new vertex between this vertex and `other` by linearly
  80646. // interpolating all properties using a parameter of `t`. Subclasses should
  80647. // override this to interpolate additional properties.
  80648. Vertex.prototype.interpolate = function (other, t) {
  80649. 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));
  80650. };
  80651. return Vertex;
  80652. }());
  80653. // # class Plane
  80654. // Represents a plane in 3D space.
  80655. var Plane = /** @class */ (function () {
  80656. function Plane(normal, w) {
  80657. this.normal = normal;
  80658. this.w = w;
  80659. }
  80660. Plane.FromPoints = function (a, b, c) {
  80661. var v0 = c.subtract(a);
  80662. var v1 = b.subtract(a);
  80663. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80664. return null;
  80665. }
  80666. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80667. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80668. };
  80669. Plane.prototype.clone = function () {
  80670. return new Plane(this.normal.clone(), this.w);
  80671. };
  80672. Plane.prototype.flip = function () {
  80673. this.normal.scaleInPlace(-1);
  80674. this.w = -this.w;
  80675. };
  80676. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80677. // fragments in the appropriate lists. Coplanar polygons go into either
  80678. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80679. // respect to this plane. Polygons in front or in back of this plane go into
  80680. // either `front` or `back`.
  80681. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80682. var COPLANAR = 0;
  80683. var FRONT = 1;
  80684. var BACK = 2;
  80685. var SPANNING = 3;
  80686. // Classify each point as well as the entire polygon into one of the above
  80687. // four classes.
  80688. var polygonType = 0;
  80689. var types = [];
  80690. var i;
  80691. var t;
  80692. for (i = 0; i < polygon.vertices.length; i++) {
  80693. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80694. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80695. polygonType |= type;
  80696. types.push(type);
  80697. }
  80698. // Put the polygon in the correct list, splitting it when necessary.
  80699. switch (polygonType) {
  80700. case COPLANAR:
  80701. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80702. break;
  80703. case FRONT:
  80704. front.push(polygon);
  80705. break;
  80706. case BACK:
  80707. back.push(polygon);
  80708. break;
  80709. case SPANNING:
  80710. var f = [], b = [];
  80711. for (i = 0; i < polygon.vertices.length; i++) {
  80712. var j = (i + 1) % polygon.vertices.length;
  80713. var ti = types[i], tj = types[j];
  80714. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80715. if (ti !== BACK)
  80716. f.push(vi);
  80717. if (ti !== FRONT)
  80718. b.push(ti !== BACK ? vi.clone() : vi);
  80719. if ((ti | tj) === SPANNING) {
  80720. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80721. var v = vi.interpolate(vj, t);
  80722. f.push(v);
  80723. b.push(v.clone());
  80724. }
  80725. }
  80726. var poly;
  80727. if (f.length >= 3) {
  80728. poly = new Polygon(f, polygon.shared);
  80729. if (poly.plane)
  80730. front.push(poly);
  80731. }
  80732. if (b.length >= 3) {
  80733. poly = new Polygon(b, polygon.shared);
  80734. if (poly.plane)
  80735. back.push(poly);
  80736. }
  80737. break;
  80738. }
  80739. };
  80740. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80741. // point is on the plane.
  80742. Plane.EPSILON = 1e-5;
  80743. return Plane;
  80744. }());
  80745. // # class Polygon
  80746. // Represents a convex polygon. The vertices used to initialize a polygon must
  80747. // be coplanar and form a convex loop.
  80748. //
  80749. // Each convex polygon has a `shared` property, which is shared between all
  80750. // polygons that are clones of each other or were split from the same polygon.
  80751. // This can be used to define per-polygon properties (such as surface color).
  80752. var Polygon = /** @class */ (function () {
  80753. function Polygon(vertices, shared) {
  80754. this.vertices = vertices;
  80755. this.shared = shared;
  80756. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80757. }
  80758. Polygon.prototype.clone = function () {
  80759. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80760. return new Polygon(vertices, this.shared);
  80761. };
  80762. Polygon.prototype.flip = function () {
  80763. this.vertices.reverse().map(function (v) { v.flip(); });
  80764. this.plane.flip();
  80765. };
  80766. return Polygon;
  80767. }());
  80768. // # class Node
  80769. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80770. // by picking a polygon to split along. That polygon (and all other coplanar
  80771. // polygons) are added directly to that node and the other polygons are added to
  80772. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80773. // no distinction between internal and leaf nodes.
  80774. var Node = /** @class */ (function () {
  80775. function Node(polygons) {
  80776. this.plane = null;
  80777. this.front = null;
  80778. this.back = null;
  80779. this.polygons = new Array();
  80780. if (polygons) {
  80781. this.build(polygons);
  80782. }
  80783. }
  80784. Node.prototype.clone = function () {
  80785. var node = new Node();
  80786. node.plane = this.plane && this.plane.clone();
  80787. node.front = this.front && this.front.clone();
  80788. node.back = this.back && this.back.clone();
  80789. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80790. return node;
  80791. };
  80792. // Convert solid space to empty space and empty space to solid space.
  80793. Node.prototype.invert = function () {
  80794. for (var i = 0; i < this.polygons.length; i++) {
  80795. this.polygons[i].flip();
  80796. }
  80797. if (this.plane) {
  80798. this.plane.flip();
  80799. }
  80800. if (this.front) {
  80801. this.front.invert();
  80802. }
  80803. if (this.back) {
  80804. this.back.invert();
  80805. }
  80806. var temp = this.front;
  80807. this.front = this.back;
  80808. this.back = temp;
  80809. };
  80810. // Recursively remove all polygons in `polygons` that are inside this BSP
  80811. // tree.
  80812. Node.prototype.clipPolygons = function (polygons) {
  80813. if (!this.plane)
  80814. return polygons.slice();
  80815. var front = new Array(), back = new Array();
  80816. for (var i = 0; i < polygons.length; i++) {
  80817. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80818. }
  80819. if (this.front) {
  80820. front = this.front.clipPolygons(front);
  80821. }
  80822. if (this.back) {
  80823. back = this.back.clipPolygons(back);
  80824. }
  80825. else {
  80826. back = [];
  80827. }
  80828. return front.concat(back);
  80829. };
  80830. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80831. // `bsp`.
  80832. Node.prototype.clipTo = function (bsp) {
  80833. this.polygons = bsp.clipPolygons(this.polygons);
  80834. if (this.front)
  80835. this.front.clipTo(bsp);
  80836. if (this.back)
  80837. this.back.clipTo(bsp);
  80838. };
  80839. // Return a list of all polygons in this BSP tree.
  80840. Node.prototype.allPolygons = function () {
  80841. var polygons = this.polygons.slice();
  80842. if (this.front)
  80843. polygons = polygons.concat(this.front.allPolygons());
  80844. if (this.back)
  80845. polygons = polygons.concat(this.back.allPolygons());
  80846. return polygons;
  80847. };
  80848. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80849. // new polygons are filtered down to the bottom of the tree and become new
  80850. // nodes there. Each set of polygons is partitioned using the first polygon
  80851. // (no heuristic is used to pick a good split).
  80852. Node.prototype.build = function (polygons) {
  80853. if (!polygons.length)
  80854. return;
  80855. if (!this.plane)
  80856. this.plane = polygons[0].plane.clone();
  80857. var front = new Array(), back = new Array();
  80858. for (var i = 0; i < polygons.length; i++) {
  80859. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80860. }
  80861. if (front.length) {
  80862. if (!this.front)
  80863. this.front = new Node();
  80864. this.front.build(front);
  80865. }
  80866. if (back.length) {
  80867. if (!this.back)
  80868. this.back = new Node();
  80869. this.back.build(back);
  80870. }
  80871. };
  80872. return Node;
  80873. }());
  80874. var CSG = /** @class */ (function () {
  80875. function CSG() {
  80876. this.polygons = new Array();
  80877. }
  80878. // Convert BABYLON.Mesh to BABYLON.CSG
  80879. CSG.FromMesh = function (mesh) {
  80880. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80881. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80882. if (mesh instanceof BABYLON.Mesh) {
  80883. mesh.computeWorldMatrix(true);
  80884. matrix = mesh.getWorldMatrix();
  80885. meshPosition = mesh.position.clone();
  80886. meshRotation = mesh.rotation.clone();
  80887. if (mesh.rotationQuaternion) {
  80888. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80889. }
  80890. meshScaling = mesh.scaling.clone();
  80891. }
  80892. else {
  80893. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80894. }
  80895. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80896. var subMeshes = mesh.subMeshes;
  80897. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80898. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80899. vertices = [];
  80900. for (var j = 0; j < 3; j++) {
  80901. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80902. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80903. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80904. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80905. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80906. vertex = new Vertex(position, normal, uv);
  80907. vertices.push(vertex);
  80908. }
  80909. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80910. // To handle the case of degenerated triangle
  80911. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80912. if (polygon.plane)
  80913. polygons.push(polygon);
  80914. }
  80915. }
  80916. var csg = CSG.FromPolygons(polygons);
  80917. csg.matrix = matrix;
  80918. csg.position = meshPosition;
  80919. csg.rotation = meshRotation;
  80920. csg.scaling = meshScaling;
  80921. csg.rotationQuaternion = meshRotationQuaternion;
  80922. currentCSGMeshId++;
  80923. return csg;
  80924. };
  80925. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80926. CSG.FromPolygons = function (polygons) {
  80927. var csg = new CSG();
  80928. csg.polygons = polygons;
  80929. return csg;
  80930. };
  80931. CSG.prototype.clone = function () {
  80932. var csg = new CSG();
  80933. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80934. csg.copyTransformAttributes(this);
  80935. return csg;
  80936. };
  80937. CSG.prototype.union = function (csg) {
  80938. var a = new Node(this.clone().polygons);
  80939. var b = new Node(csg.clone().polygons);
  80940. a.clipTo(b);
  80941. b.clipTo(a);
  80942. b.invert();
  80943. b.clipTo(a);
  80944. b.invert();
  80945. a.build(b.allPolygons());
  80946. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80947. };
  80948. CSG.prototype.unionInPlace = function (csg) {
  80949. var a = new Node(this.polygons);
  80950. var b = new Node(csg.polygons);
  80951. a.clipTo(b);
  80952. b.clipTo(a);
  80953. b.invert();
  80954. b.clipTo(a);
  80955. b.invert();
  80956. a.build(b.allPolygons());
  80957. this.polygons = a.allPolygons();
  80958. };
  80959. CSG.prototype.subtract = function (csg) {
  80960. var a = new Node(this.clone().polygons);
  80961. var b = new Node(csg.clone().polygons);
  80962. a.invert();
  80963. a.clipTo(b);
  80964. b.clipTo(a);
  80965. b.invert();
  80966. b.clipTo(a);
  80967. b.invert();
  80968. a.build(b.allPolygons());
  80969. a.invert();
  80970. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80971. };
  80972. CSG.prototype.subtractInPlace = function (csg) {
  80973. var a = new Node(this.polygons);
  80974. var b = new Node(csg.polygons);
  80975. a.invert();
  80976. a.clipTo(b);
  80977. b.clipTo(a);
  80978. b.invert();
  80979. b.clipTo(a);
  80980. b.invert();
  80981. a.build(b.allPolygons());
  80982. a.invert();
  80983. this.polygons = a.allPolygons();
  80984. };
  80985. CSG.prototype.intersect = function (csg) {
  80986. var a = new Node(this.clone().polygons);
  80987. var b = new Node(csg.clone().polygons);
  80988. a.invert();
  80989. b.clipTo(a);
  80990. b.invert();
  80991. a.clipTo(b);
  80992. b.clipTo(a);
  80993. a.build(b.allPolygons());
  80994. a.invert();
  80995. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80996. };
  80997. CSG.prototype.intersectInPlace = function (csg) {
  80998. var a = new Node(this.polygons);
  80999. var b = new Node(csg.polygons);
  81000. a.invert();
  81001. b.clipTo(a);
  81002. b.invert();
  81003. a.clipTo(b);
  81004. b.clipTo(a);
  81005. a.build(b.allPolygons());
  81006. a.invert();
  81007. this.polygons = a.allPolygons();
  81008. };
  81009. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81010. // not modified.
  81011. CSG.prototype.inverse = function () {
  81012. var csg = this.clone();
  81013. csg.inverseInPlace();
  81014. return csg;
  81015. };
  81016. CSG.prototype.inverseInPlace = function () {
  81017. this.polygons.map(function (p) { p.flip(); });
  81018. };
  81019. // This is used to keep meshes transformations so they can be restored
  81020. // when we build back a Babylon Mesh
  81021. // NB : All CSG operations are performed in world coordinates
  81022. CSG.prototype.copyTransformAttributes = function (csg) {
  81023. this.matrix = csg.matrix;
  81024. this.position = csg.position;
  81025. this.rotation = csg.rotation;
  81026. this.scaling = csg.scaling;
  81027. this.rotationQuaternion = csg.rotationQuaternion;
  81028. return this;
  81029. };
  81030. // Build Raw mesh from CSG
  81031. // Coordinates here are in world space
  81032. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81033. var matrix = this.matrix.clone();
  81034. matrix.invert();
  81035. 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;
  81036. if (keepSubMeshes) {
  81037. // Sort Polygons, since subMeshes are indices range
  81038. polygons.sort(function (a, b) {
  81039. if (a.shared.meshId === b.shared.meshId) {
  81040. return a.shared.subMeshId - b.shared.subMeshId;
  81041. }
  81042. else {
  81043. return a.shared.meshId - b.shared.meshId;
  81044. }
  81045. });
  81046. }
  81047. for (var i = 0, il = polygons.length; i < il; i++) {
  81048. polygon = polygons[i];
  81049. // Building SubMeshes
  81050. if (!subMesh_dict[polygon.shared.meshId]) {
  81051. subMesh_dict[polygon.shared.meshId] = {};
  81052. }
  81053. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81054. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81055. indexStart: +Infinity,
  81056. indexEnd: -Infinity,
  81057. materialIndex: polygon.shared.materialIndex
  81058. };
  81059. }
  81060. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81061. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81062. polygonIndices[0] = 0;
  81063. polygonIndices[1] = j - 1;
  81064. polygonIndices[2] = j;
  81065. for (var k = 0; k < 3; k++) {
  81066. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81067. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81068. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81069. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81070. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81071. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81072. // Check if 2 points can be merged
  81073. if (!(typeof vertex_idx !== 'undefined' &&
  81074. normals[vertex_idx * 3] === localNormal.x &&
  81075. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81076. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81077. uvs[vertex_idx * 2] === uv.x &&
  81078. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81079. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81080. uvs.push(uv.x, uv.y);
  81081. normals.push(normal.x, normal.y, normal.z);
  81082. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81083. }
  81084. indices.push(vertex_idx);
  81085. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81086. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81087. currentIndex++;
  81088. }
  81089. }
  81090. }
  81091. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81092. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81093. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81094. mesh.setIndices(indices, null);
  81095. if (keepSubMeshes) {
  81096. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81097. var materialIndexOffset = 0, materialMaxIndex;
  81098. mesh.subMeshes = new Array();
  81099. for (var m in subMesh_dict) {
  81100. materialMaxIndex = -1;
  81101. for (var sm in subMesh_dict[m]) {
  81102. subMesh_obj = subMesh_dict[m][sm];
  81103. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81104. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81105. }
  81106. materialIndexOffset += ++materialMaxIndex;
  81107. }
  81108. }
  81109. return mesh;
  81110. };
  81111. // Build Mesh from CSG taking material and transforms into account
  81112. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81113. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81114. mesh.material = material;
  81115. mesh.position.copyFrom(this.position);
  81116. mesh.rotation.copyFrom(this.rotation);
  81117. if (this.rotationQuaternion) {
  81118. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81119. }
  81120. mesh.scaling.copyFrom(this.scaling);
  81121. mesh.computeWorldMatrix(true);
  81122. return mesh;
  81123. };
  81124. return CSG;
  81125. }());
  81126. BABYLON.CSG = CSG;
  81127. })(BABYLON || (BABYLON = {}));
  81128. //# sourceMappingURL=babylon.csg.js.map
  81129. var BABYLON;
  81130. (function (BABYLON) {
  81131. var LensFlare = /** @class */ (function () {
  81132. function LensFlare(size, position, color, imgUrl, system) {
  81133. this.size = size;
  81134. this.position = position;
  81135. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81136. this.color = color || new BABYLON.Color3(1, 1, 1);
  81137. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81138. this._system = system;
  81139. system.lensFlares.push(this);
  81140. }
  81141. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81142. return new LensFlare(size, position, color, imgUrl, system);
  81143. };
  81144. LensFlare.prototype.dispose = function () {
  81145. if (this.texture) {
  81146. this.texture.dispose();
  81147. }
  81148. // Remove from scene
  81149. var index = this._system.lensFlares.indexOf(this);
  81150. this._system.lensFlares.splice(index, 1);
  81151. };
  81152. ;
  81153. return LensFlare;
  81154. }());
  81155. BABYLON.LensFlare = LensFlare;
  81156. })(BABYLON || (BABYLON = {}));
  81157. //# sourceMappingURL=babylon.lensFlare.js.map
  81158. var BABYLON;
  81159. (function (BABYLON) {
  81160. var LensFlareSystem = /** @class */ (function () {
  81161. function LensFlareSystem(name, emitter, scene) {
  81162. this.name = name;
  81163. this.lensFlares = new Array();
  81164. this.borderLimit = 300;
  81165. this.viewportBorder = 0;
  81166. this.layerMask = 0x0FFFFFFF;
  81167. this._vertexBuffers = {};
  81168. this._isEnabled = true;
  81169. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81170. this._emitter = emitter;
  81171. this.id = name;
  81172. scene.lensFlareSystems.push(this);
  81173. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81174. var engine = scene.getEngine();
  81175. // VBO
  81176. var vertices = [];
  81177. vertices.push(1, 1);
  81178. vertices.push(-1, 1);
  81179. vertices.push(-1, -1);
  81180. vertices.push(1, -1);
  81181. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81182. // Indices
  81183. var indices = [];
  81184. indices.push(0);
  81185. indices.push(1);
  81186. indices.push(2);
  81187. indices.push(0);
  81188. indices.push(2);
  81189. indices.push(3);
  81190. this._indexBuffer = engine.createIndexBuffer(indices);
  81191. // Effects
  81192. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81193. }
  81194. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81195. get: function () {
  81196. return this._isEnabled;
  81197. },
  81198. set: function (value) {
  81199. this._isEnabled = value;
  81200. },
  81201. enumerable: true,
  81202. configurable: true
  81203. });
  81204. LensFlareSystem.prototype.getScene = function () {
  81205. return this._scene;
  81206. };
  81207. LensFlareSystem.prototype.getEmitter = function () {
  81208. return this._emitter;
  81209. };
  81210. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81211. this._emitter = newEmitter;
  81212. };
  81213. LensFlareSystem.prototype.getEmitterPosition = function () {
  81214. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81215. };
  81216. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81217. var position = this.getEmitterPosition();
  81218. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81219. this._positionX = position.x;
  81220. this._positionY = position.y;
  81221. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81222. if (this.viewportBorder > 0) {
  81223. globalViewport.x -= this.viewportBorder;
  81224. globalViewport.y -= this.viewportBorder;
  81225. globalViewport.width += this.viewportBorder * 2;
  81226. globalViewport.height += this.viewportBorder * 2;
  81227. position.x += this.viewportBorder;
  81228. position.y += this.viewportBorder;
  81229. this._positionX += this.viewportBorder;
  81230. this._positionY += this.viewportBorder;
  81231. }
  81232. if (position.z > 0) {
  81233. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81234. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81235. return true;
  81236. }
  81237. return true;
  81238. }
  81239. return false;
  81240. };
  81241. LensFlareSystem.prototype._isVisible = function () {
  81242. if (!this._isEnabled || !this._scene.activeCamera) {
  81243. return false;
  81244. }
  81245. var emitterPosition = this.getEmitterPosition();
  81246. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81247. var distance = direction.length();
  81248. direction.normalize();
  81249. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81250. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81251. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81252. };
  81253. LensFlareSystem.prototype.render = function () {
  81254. if (!this._effect.isReady() || !this._scene.activeCamera)
  81255. return false;
  81256. var engine = this._scene.getEngine();
  81257. var viewport = this._scene.activeCamera.viewport;
  81258. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81259. // Position
  81260. if (!this.computeEffectivePosition(globalViewport)) {
  81261. return false;
  81262. }
  81263. // Visibility
  81264. if (!this._isVisible()) {
  81265. return false;
  81266. }
  81267. // Intensity
  81268. var awayX;
  81269. var awayY;
  81270. if (this._positionX < this.borderLimit + globalViewport.x) {
  81271. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81272. }
  81273. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81274. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81275. }
  81276. else {
  81277. awayX = 0;
  81278. }
  81279. if (this._positionY < this.borderLimit + globalViewport.y) {
  81280. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81281. }
  81282. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81283. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81284. }
  81285. else {
  81286. awayY = 0;
  81287. }
  81288. var away = (awayX > awayY) ? awayX : awayY;
  81289. away -= this.viewportBorder;
  81290. if (away > this.borderLimit) {
  81291. away = this.borderLimit;
  81292. }
  81293. var intensity = 1.0 - (away / this.borderLimit);
  81294. if (intensity < 0) {
  81295. return false;
  81296. }
  81297. if (intensity > 1.0) {
  81298. intensity = 1.0;
  81299. }
  81300. if (this.viewportBorder > 0) {
  81301. globalViewport.x += this.viewportBorder;
  81302. globalViewport.y += this.viewportBorder;
  81303. globalViewport.width -= this.viewportBorder * 2;
  81304. globalViewport.height -= this.viewportBorder * 2;
  81305. this._positionX -= this.viewportBorder;
  81306. this._positionY -= this.viewportBorder;
  81307. }
  81308. // Position
  81309. var centerX = globalViewport.x + globalViewport.width / 2;
  81310. var centerY = globalViewport.y + globalViewport.height / 2;
  81311. var distX = centerX - this._positionX;
  81312. var distY = centerY - this._positionY;
  81313. // Effects
  81314. engine.enableEffect(this._effect);
  81315. engine.setState(false);
  81316. engine.setDepthBuffer(false);
  81317. // VBOs
  81318. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81319. // Flares
  81320. for (var index = 0; index < this.lensFlares.length; index++) {
  81321. var flare = this.lensFlares[index];
  81322. engine.setAlphaMode(flare.alphaMode);
  81323. var x = centerX - (distX * flare.position);
  81324. var y = centerY - (distY * flare.position);
  81325. var cw = flare.size;
  81326. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81327. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81328. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81329. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81330. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81331. // Texture
  81332. this._effect.setTexture("textureSampler", flare.texture);
  81333. // Color
  81334. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81335. // Draw order
  81336. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81337. }
  81338. engine.setDepthBuffer(true);
  81339. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81340. return true;
  81341. };
  81342. LensFlareSystem.prototype.dispose = function () {
  81343. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81344. if (vertexBuffer) {
  81345. vertexBuffer.dispose();
  81346. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81347. }
  81348. if (this._indexBuffer) {
  81349. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81350. this._indexBuffer = null;
  81351. }
  81352. while (this.lensFlares.length) {
  81353. this.lensFlares[0].dispose();
  81354. }
  81355. // Remove from scene
  81356. var index = this._scene.lensFlareSystems.indexOf(this);
  81357. this._scene.lensFlareSystems.splice(index, 1);
  81358. };
  81359. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81360. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81361. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81362. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81363. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81364. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81365. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81366. var parsedFlare = parsedLensFlareSystem.flares[index];
  81367. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81368. }
  81369. return lensFlareSystem;
  81370. };
  81371. LensFlareSystem.prototype.serialize = function () {
  81372. var serializationObject = {};
  81373. serializationObject.id = this.id;
  81374. serializationObject.name = this.name;
  81375. serializationObject.emitterId = this.getEmitter().id;
  81376. serializationObject.borderLimit = this.borderLimit;
  81377. serializationObject.flares = [];
  81378. for (var index = 0; index < this.lensFlares.length; index++) {
  81379. var flare = this.lensFlares[index];
  81380. serializationObject.flares.push({
  81381. size: flare.size,
  81382. position: flare.position,
  81383. color: flare.color.asArray(),
  81384. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81385. });
  81386. }
  81387. return serializationObject;
  81388. };
  81389. return LensFlareSystem;
  81390. }());
  81391. BABYLON.LensFlareSystem = LensFlareSystem;
  81392. })(BABYLON || (BABYLON = {}));
  81393. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81394. var BABYLON;
  81395. (function (BABYLON) {
  81396. /**
  81397. * This is a holder class for the physics joint created by the physics plugin.
  81398. * It holds a set of functions to control the underlying joint.
  81399. */
  81400. var PhysicsJoint = /** @class */ (function () {
  81401. function PhysicsJoint(type, jointData) {
  81402. this.type = type;
  81403. this.jointData = jointData;
  81404. jointData.nativeParams = jointData.nativeParams || {};
  81405. }
  81406. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81407. get: function () {
  81408. return this._physicsJoint;
  81409. },
  81410. set: function (newJoint) {
  81411. if (this._physicsJoint) {
  81412. //remove from the wolrd
  81413. }
  81414. this._physicsJoint = newJoint;
  81415. },
  81416. enumerable: true,
  81417. configurable: true
  81418. });
  81419. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81420. set: function (physicsPlugin) {
  81421. this._physicsPlugin = physicsPlugin;
  81422. },
  81423. enumerable: true,
  81424. configurable: true
  81425. });
  81426. /**
  81427. * Execute a function that is physics-plugin specific.
  81428. * @param {Function} func the function that will be executed.
  81429. * It accepts two parameters: the physics world and the physics joint.
  81430. */
  81431. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81432. func(this._physicsPlugin.world, this._physicsJoint);
  81433. };
  81434. //TODO check if the native joints are the same
  81435. //Joint Types
  81436. PhysicsJoint.DistanceJoint = 0;
  81437. PhysicsJoint.HingeJoint = 1;
  81438. PhysicsJoint.BallAndSocketJoint = 2;
  81439. PhysicsJoint.WheelJoint = 3;
  81440. PhysicsJoint.SliderJoint = 4;
  81441. //OIMO
  81442. PhysicsJoint.PrismaticJoint = 5;
  81443. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81444. PhysicsJoint.UniversalJoint = 6;
  81445. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81446. //Cannon
  81447. //Similar to a Ball-Joint. Different in params
  81448. PhysicsJoint.PointToPointJoint = 8;
  81449. //Cannon only at the moment
  81450. PhysicsJoint.SpringJoint = 9;
  81451. PhysicsJoint.LockJoint = 10;
  81452. return PhysicsJoint;
  81453. }());
  81454. BABYLON.PhysicsJoint = PhysicsJoint;
  81455. /**
  81456. * A class representing a physics distance joint.
  81457. */
  81458. var DistanceJoint = /** @class */ (function (_super) {
  81459. __extends(DistanceJoint, _super);
  81460. function DistanceJoint(jointData) {
  81461. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81462. }
  81463. /**
  81464. * Update the predefined distance.
  81465. */
  81466. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81467. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81468. };
  81469. return DistanceJoint;
  81470. }(PhysicsJoint));
  81471. BABYLON.DistanceJoint = DistanceJoint;
  81472. var MotorEnabledJoint = /** @class */ (function (_super) {
  81473. __extends(MotorEnabledJoint, _super);
  81474. function MotorEnabledJoint(type, jointData) {
  81475. return _super.call(this, type, jointData) || this;
  81476. }
  81477. /**
  81478. * Set the motor values.
  81479. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81480. * @param {number} force the force to apply
  81481. * @param {number} maxForce max force for this motor.
  81482. */
  81483. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81484. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81485. };
  81486. /**
  81487. * Set the motor's limits.
  81488. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81489. */
  81490. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81491. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81492. };
  81493. return MotorEnabledJoint;
  81494. }(PhysicsJoint));
  81495. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81496. /**
  81497. * This class represents a single hinge physics joint
  81498. */
  81499. var HingeJoint = /** @class */ (function (_super) {
  81500. __extends(HingeJoint, _super);
  81501. function HingeJoint(jointData) {
  81502. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81503. }
  81504. /**
  81505. * Set the motor values.
  81506. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81507. * @param {number} force the force to apply
  81508. * @param {number} maxForce max force for this motor.
  81509. */
  81510. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81511. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81512. };
  81513. /**
  81514. * Set the motor's limits.
  81515. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81516. */
  81517. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81518. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81519. };
  81520. return HingeJoint;
  81521. }(MotorEnabledJoint));
  81522. BABYLON.HingeJoint = HingeJoint;
  81523. /**
  81524. * This class represents a dual hinge physics joint (same as wheel joint)
  81525. */
  81526. var Hinge2Joint = /** @class */ (function (_super) {
  81527. __extends(Hinge2Joint, _super);
  81528. function Hinge2Joint(jointData) {
  81529. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81530. }
  81531. /**
  81532. * Set the motor values.
  81533. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81534. * @param {number} force the force to apply
  81535. * @param {number} maxForce max force for this motor.
  81536. * @param {motorIndex} the motor's index, 0 or 1.
  81537. */
  81538. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81539. if (motorIndex === void 0) { motorIndex = 0; }
  81540. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81541. };
  81542. /**
  81543. * Set the motor limits.
  81544. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81545. * @param {number} upperLimit the upper limit
  81546. * @param {number} lowerLimit lower limit
  81547. * @param {motorIndex} the motor's index, 0 or 1.
  81548. */
  81549. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81550. if (motorIndex === void 0) { motorIndex = 0; }
  81551. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81552. };
  81553. return Hinge2Joint;
  81554. }(MotorEnabledJoint));
  81555. BABYLON.Hinge2Joint = Hinge2Joint;
  81556. })(BABYLON || (BABYLON = {}));
  81557. //# sourceMappingURL=babylon.physicsJoint.js.map
  81558. var BABYLON;
  81559. (function (BABYLON) {
  81560. var PhysicsImpostor = /** @class */ (function () {
  81561. function PhysicsImpostor(object, type, _options, _scene) {
  81562. if (_options === void 0) { _options = { mass: 0 }; }
  81563. var _this = this;
  81564. this.object = object;
  81565. this.type = type;
  81566. this._options = _options;
  81567. this._scene = _scene;
  81568. this._bodyUpdateRequired = false;
  81569. this._onBeforePhysicsStepCallbacks = new Array();
  81570. this._onAfterPhysicsStepCallbacks = new Array();
  81571. this._onPhysicsCollideCallbacks = [];
  81572. this._deltaPosition = BABYLON.Vector3.Zero();
  81573. this._isDisposed = false;
  81574. //temp variables for parent rotation calculations
  81575. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81576. this._tmpQuat = new BABYLON.Quaternion();
  81577. this._tmpQuat2 = new BABYLON.Quaternion();
  81578. /**
  81579. * this function is executed by the physics engine.
  81580. */
  81581. this.beforeStep = function () {
  81582. if (!_this._physicsEngine) {
  81583. return;
  81584. }
  81585. _this.object.translate(_this._deltaPosition, -1);
  81586. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81587. _this.object.computeWorldMatrix(false);
  81588. if (_this.object.parent && _this.object.rotationQuaternion) {
  81589. _this.getParentsRotation();
  81590. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81591. }
  81592. else {
  81593. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81594. }
  81595. if (!_this._options.disableBidirectionalTransformation) {
  81596. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81597. }
  81598. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81599. func(_this);
  81600. });
  81601. };
  81602. /**
  81603. * this function is executed by the physics engine.
  81604. */
  81605. this.afterStep = function () {
  81606. if (!_this._physicsEngine) {
  81607. return;
  81608. }
  81609. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81610. func(_this);
  81611. });
  81612. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81613. // object has now its world rotation. needs to be converted to local.
  81614. if (_this.object.parent && _this.object.rotationQuaternion) {
  81615. _this.getParentsRotation();
  81616. _this._tmpQuat.conjugateInPlace();
  81617. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81618. }
  81619. // take the position set and make it the absolute position of this object.
  81620. _this.object.setAbsolutePosition(_this.object.position);
  81621. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81622. _this.object.translate(_this._deltaPosition, 1);
  81623. };
  81624. /**
  81625. * Legacy collision detection event support
  81626. */
  81627. this.onCollideEvent = null;
  81628. //event and body object due to cannon's event-based architecture.
  81629. this.onCollide = function (e) {
  81630. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81631. return;
  81632. }
  81633. if (!_this._physicsEngine) {
  81634. return;
  81635. }
  81636. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81637. if (otherImpostor) {
  81638. // Legacy collision detection event support
  81639. if (_this.onCollideEvent) {
  81640. _this.onCollideEvent(_this, otherImpostor);
  81641. }
  81642. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81643. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81644. }).forEach(function (obj) {
  81645. obj.callback(_this, otherImpostor);
  81646. });
  81647. }
  81648. };
  81649. //sanity check!
  81650. if (!this.object) {
  81651. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81652. return;
  81653. }
  81654. //legacy support for old syntax.
  81655. if (!this._scene && object.getScene) {
  81656. this._scene = object.getScene();
  81657. }
  81658. if (!this._scene) {
  81659. return;
  81660. }
  81661. this._physicsEngine = this._scene.getPhysicsEngine();
  81662. if (!this._physicsEngine) {
  81663. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81664. }
  81665. else {
  81666. //set the object's quaternion, if not set
  81667. if (!this.object.rotationQuaternion) {
  81668. if (this.object.rotation) {
  81669. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81670. }
  81671. else {
  81672. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81673. }
  81674. }
  81675. //default options params
  81676. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81677. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81678. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81679. this._joints = [];
  81680. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81681. if (!this.object.parent || this._options.ignoreParent) {
  81682. this._init();
  81683. }
  81684. else if (this.object.parent.physicsImpostor) {
  81685. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81686. }
  81687. }
  81688. }
  81689. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81690. get: function () {
  81691. return this._isDisposed;
  81692. },
  81693. enumerable: true,
  81694. configurable: true
  81695. });
  81696. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81697. get: function () {
  81698. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81699. },
  81700. set: function (value) {
  81701. this.setMass(value);
  81702. },
  81703. enumerable: true,
  81704. configurable: true
  81705. });
  81706. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81707. get: function () {
  81708. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81709. },
  81710. set: function (value) {
  81711. if (!this._physicsEngine) {
  81712. return;
  81713. }
  81714. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81715. },
  81716. enumerable: true,
  81717. configurable: true
  81718. });
  81719. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81720. get: function () {
  81721. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81722. },
  81723. set: function (value) {
  81724. if (!this._physicsEngine) {
  81725. return;
  81726. }
  81727. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81728. },
  81729. enumerable: true,
  81730. configurable: true
  81731. });
  81732. /**
  81733. * This function will completly initialize this impostor.
  81734. * It will create a new body - but only if this mesh has no parent.
  81735. * If it has, this impostor will not be used other than to define the impostor
  81736. * of the child mesh.
  81737. */
  81738. PhysicsImpostor.prototype._init = function () {
  81739. if (!this._physicsEngine) {
  81740. return;
  81741. }
  81742. this._physicsEngine.removeImpostor(this);
  81743. this.physicsBody = null;
  81744. this._parent = this._parent || this._getPhysicsParent();
  81745. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81746. this._physicsEngine.addImpostor(this);
  81747. }
  81748. };
  81749. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81750. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81751. var parentMesh = this.object.parent;
  81752. return parentMesh.physicsImpostor;
  81753. }
  81754. return null;
  81755. };
  81756. /**
  81757. * Should a new body be generated.
  81758. */
  81759. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81760. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81761. };
  81762. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81763. this.forceUpdate();
  81764. };
  81765. /**
  81766. * Force a regeneration of this or the parent's impostor's body.
  81767. * Use under cautious - This will remove all joints already implemented.
  81768. */
  81769. PhysicsImpostor.prototype.forceUpdate = function () {
  81770. this._init();
  81771. if (this.parent && !this._options.ignoreParent) {
  81772. this.parent.forceUpdate();
  81773. }
  81774. };
  81775. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81776. /*public get mesh(): AbstractMesh {
  81777. return this._mesh;
  81778. }*/
  81779. /**
  81780. * Gets the body that holds this impostor. Either its own, or its parent.
  81781. */
  81782. get: function () {
  81783. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81784. },
  81785. /**
  81786. * Set the physics body. Used mainly by the physics engine/plugin
  81787. */
  81788. set: function (physicsBody) {
  81789. if (this._physicsBody && this._physicsEngine) {
  81790. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81791. }
  81792. this._physicsBody = physicsBody;
  81793. this.resetUpdateFlags();
  81794. },
  81795. enumerable: true,
  81796. configurable: true
  81797. });
  81798. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81799. get: function () {
  81800. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81801. },
  81802. set: function (value) {
  81803. this._parent = value;
  81804. },
  81805. enumerable: true,
  81806. configurable: true
  81807. });
  81808. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81809. this._bodyUpdateRequired = false;
  81810. };
  81811. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81812. if (this.object.getBoundingInfo) {
  81813. var q = this.object.rotationQuaternion;
  81814. //reset rotation
  81815. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81816. //calculate the world matrix with no rotation
  81817. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81818. var boundingInfo = this.object.getBoundingInfo();
  81819. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81820. //bring back the rotation
  81821. this.object.rotationQuaternion = q;
  81822. //calculate the world matrix with the new rotation
  81823. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81824. return size;
  81825. }
  81826. else {
  81827. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81828. }
  81829. };
  81830. PhysicsImpostor.prototype.getObjectCenter = function () {
  81831. if (this.object.getBoundingInfo) {
  81832. var boundingInfo = this.object.getBoundingInfo();
  81833. return boundingInfo.boundingBox.centerWorld;
  81834. }
  81835. else {
  81836. return this.object.position;
  81837. }
  81838. };
  81839. /**
  81840. * Get a specific parametes from the options parameter.
  81841. */
  81842. PhysicsImpostor.prototype.getParam = function (paramName) {
  81843. return this._options[paramName];
  81844. };
  81845. /**
  81846. * Sets a specific parameter in the options given to the physics plugin
  81847. */
  81848. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81849. this._options[paramName] = value;
  81850. this._bodyUpdateRequired = true;
  81851. };
  81852. /**
  81853. * Specifically change the body's mass option. Won't recreate the physics body object
  81854. */
  81855. PhysicsImpostor.prototype.setMass = function (mass) {
  81856. if (this.getParam("mass") !== mass) {
  81857. this.setParam("mass", mass);
  81858. }
  81859. if (this._physicsEngine) {
  81860. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81861. }
  81862. };
  81863. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81864. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81865. };
  81866. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81867. if (this._physicsEngine) {
  81868. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81869. }
  81870. };
  81871. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81872. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81873. };
  81874. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81875. if (this._physicsEngine) {
  81876. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81877. }
  81878. };
  81879. /**
  81880. * Execute a function with the physics plugin native code.
  81881. * Provide a function the will have two variables - the world object and the physics body object.
  81882. */
  81883. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81884. if (this._physicsEngine) {
  81885. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81886. }
  81887. };
  81888. /**
  81889. * Register a function that will be executed before the physics world is stepping forward.
  81890. */
  81891. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81892. this._onBeforePhysicsStepCallbacks.push(func);
  81893. };
  81894. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81895. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81896. if (index > -1) {
  81897. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81898. }
  81899. else {
  81900. BABYLON.Tools.Warn("Function to remove was not found");
  81901. }
  81902. };
  81903. /**
  81904. * Register a function that will be executed after the physics step
  81905. */
  81906. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81907. this._onAfterPhysicsStepCallbacks.push(func);
  81908. };
  81909. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81910. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81911. if (index > -1) {
  81912. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81913. }
  81914. else {
  81915. BABYLON.Tools.Warn("Function to remove was not found");
  81916. }
  81917. };
  81918. /**
  81919. * register a function that will be executed when this impostor collides against a different body.
  81920. */
  81921. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81922. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81923. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81924. };
  81925. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81926. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81927. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81928. if (index > -1) {
  81929. this._onPhysicsCollideCallbacks.splice(index, 1);
  81930. }
  81931. else {
  81932. BABYLON.Tools.Warn("Function to remove was not found");
  81933. }
  81934. };
  81935. PhysicsImpostor.prototype.getParentsRotation = function () {
  81936. var parent = this.object.parent;
  81937. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  81938. while (parent) {
  81939. if (parent.rotationQuaternion) {
  81940. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  81941. }
  81942. else {
  81943. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  81944. }
  81945. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  81946. parent = parent.parent;
  81947. }
  81948. return this._tmpQuat;
  81949. };
  81950. /**
  81951. * Apply a force
  81952. */
  81953. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  81954. if (this._physicsEngine) {
  81955. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  81956. }
  81957. return this;
  81958. };
  81959. /**
  81960. * Apply an impulse
  81961. */
  81962. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  81963. if (this._physicsEngine) {
  81964. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  81965. }
  81966. return this;
  81967. };
  81968. /**
  81969. * A help function to create a joint.
  81970. */
  81971. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  81972. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  81973. this.addJoint(otherImpostor, joint);
  81974. return this;
  81975. };
  81976. /**
  81977. * Add a joint to this impostor with a different impostor.
  81978. */
  81979. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  81980. this._joints.push({
  81981. otherImpostor: otherImpostor,
  81982. joint: joint
  81983. });
  81984. if (this._physicsEngine) {
  81985. this._physicsEngine.addJoint(this, otherImpostor, joint);
  81986. }
  81987. return this;
  81988. };
  81989. /**
  81990. * Will keep this body still, in a sleep mode.
  81991. */
  81992. PhysicsImpostor.prototype.sleep = function () {
  81993. if (this._physicsEngine) {
  81994. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  81995. }
  81996. return this;
  81997. };
  81998. /**
  81999. * Wake the body up.
  82000. */
  82001. PhysicsImpostor.prototype.wakeUp = function () {
  82002. if (this._physicsEngine) {
  82003. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82004. }
  82005. return this;
  82006. };
  82007. PhysicsImpostor.prototype.clone = function (newObject) {
  82008. if (!newObject)
  82009. return null;
  82010. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82011. };
  82012. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82013. var _this = this;
  82014. //no dispose if no physics engine is available.
  82015. if (!this._physicsEngine) {
  82016. return;
  82017. }
  82018. this._joints.forEach(function (j) {
  82019. if (_this._physicsEngine) {
  82020. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82021. }
  82022. });
  82023. //dispose the physics body
  82024. this._physicsEngine.removeImpostor(this);
  82025. if (this.parent) {
  82026. this.parent.forceUpdate();
  82027. }
  82028. else {
  82029. /*this._object.getChildMeshes().forEach(function(mesh) {
  82030. if (mesh.physicsImpostor) {
  82031. if (disposeChildren) {
  82032. mesh.physicsImpostor.dispose();
  82033. mesh.physicsImpostor = null;
  82034. }
  82035. }
  82036. })*/
  82037. }
  82038. this._isDisposed = true;
  82039. };
  82040. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82041. this._deltaPosition.copyFrom(position);
  82042. };
  82043. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82044. if (!this._deltaRotation) {
  82045. this._deltaRotation = new BABYLON.Quaternion();
  82046. }
  82047. this._deltaRotation.copyFrom(rotation);
  82048. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82049. };
  82050. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82051. if (this._physicsEngine) {
  82052. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82053. }
  82054. return this;
  82055. };
  82056. PhysicsImpostor.prototype.getRadius = function () {
  82057. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82058. };
  82059. /**
  82060. * Sync a bone with this impostor
  82061. * @param bone The bone to sync to the impostor.
  82062. * @param boneMesh The mesh that the bone is influencing.
  82063. * @param jointPivot The pivot of the joint / bone in local space.
  82064. * @param distToJoint Optional distance from the impostor to the joint.
  82065. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82066. */
  82067. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82068. var tempVec = PhysicsImpostor._tmpVecs[0];
  82069. var mesh = this.object;
  82070. if (mesh.rotationQuaternion) {
  82071. if (adjustRotation) {
  82072. var tempQuat = PhysicsImpostor._tmpQuat;
  82073. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82074. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82075. }
  82076. else {
  82077. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82078. }
  82079. }
  82080. tempVec.x = 0;
  82081. tempVec.y = 0;
  82082. tempVec.z = 0;
  82083. if (jointPivot) {
  82084. tempVec.x = jointPivot.x;
  82085. tempVec.y = jointPivot.y;
  82086. tempVec.z = jointPivot.z;
  82087. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82088. if (distToJoint === undefined || distToJoint === null) {
  82089. distToJoint = jointPivot.length();
  82090. }
  82091. tempVec.x *= distToJoint;
  82092. tempVec.y *= distToJoint;
  82093. tempVec.z *= distToJoint;
  82094. }
  82095. if (bone.getParent()) {
  82096. tempVec.addInPlace(mesh.getAbsolutePosition());
  82097. bone.setAbsolutePosition(tempVec, boneMesh);
  82098. }
  82099. else {
  82100. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82101. boneMesh.position.x -= tempVec.x;
  82102. boneMesh.position.y -= tempVec.y;
  82103. boneMesh.position.z -= tempVec.z;
  82104. }
  82105. };
  82106. /**
  82107. * Sync impostor to a bone
  82108. * @param bone The bone that the impostor will be synced to.
  82109. * @param boneMesh The mesh that the bone is influencing.
  82110. * @param jointPivot The pivot of the joint / bone in local space.
  82111. * @param distToJoint Optional distance from the impostor to the joint.
  82112. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82113. * @param boneAxis Optional vector3 axis the bone is aligned with
  82114. */
  82115. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82116. var mesh = this.object;
  82117. if (mesh.rotationQuaternion) {
  82118. if (adjustRotation) {
  82119. var tempQuat = PhysicsImpostor._tmpQuat;
  82120. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82121. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82122. }
  82123. else {
  82124. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82125. }
  82126. }
  82127. var pos = PhysicsImpostor._tmpVecs[0];
  82128. var boneDir = PhysicsImpostor._tmpVecs[1];
  82129. if (!boneAxis) {
  82130. boneAxis = PhysicsImpostor._tmpVecs[2];
  82131. boneAxis.x = 0;
  82132. boneAxis.y = 1;
  82133. boneAxis.z = 0;
  82134. }
  82135. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82136. bone.getAbsolutePositionToRef(boneMesh, pos);
  82137. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82138. distToJoint = jointPivot.length();
  82139. }
  82140. if (distToJoint !== undefined && distToJoint !== null) {
  82141. pos.x += boneDir.x * distToJoint;
  82142. pos.y += boneDir.y * distToJoint;
  82143. pos.z += boneDir.z * distToJoint;
  82144. }
  82145. mesh.setAbsolutePosition(pos);
  82146. };
  82147. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82148. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82149. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82150. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82151. //Impostor types
  82152. PhysicsImpostor.NoImpostor = 0;
  82153. PhysicsImpostor.SphereImpostor = 1;
  82154. PhysicsImpostor.BoxImpostor = 2;
  82155. PhysicsImpostor.PlaneImpostor = 3;
  82156. PhysicsImpostor.MeshImpostor = 4;
  82157. PhysicsImpostor.CylinderImpostor = 7;
  82158. PhysicsImpostor.ParticleImpostor = 8;
  82159. PhysicsImpostor.HeightmapImpostor = 9;
  82160. return PhysicsImpostor;
  82161. }());
  82162. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82163. })(BABYLON || (BABYLON = {}));
  82164. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82165. var BABYLON;
  82166. (function (BABYLON) {
  82167. var PhysicsEngine = /** @class */ (function () {
  82168. function PhysicsEngine(gravity, _physicsPlugin) {
  82169. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82170. this._physicsPlugin = _physicsPlugin;
  82171. //new methods and parameters
  82172. this._impostors = [];
  82173. this._joints = [];
  82174. if (!this._physicsPlugin.isSupported()) {
  82175. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82176. + "Please make sure it is included.");
  82177. }
  82178. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82179. this.setGravity(gravity);
  82180. this.setTimeStep();
  82181. }
  82182. PhysicsEngine.prototype.setGravity = function (gravity) {
  82183. this.gravity = gravity;
  82184. this._physicsPlugin.setGravity(this.gravity);
  82185. };
  82186. /**
  82187. * Set the time step of the physics engine.
  82188. * default is 1/60.
  82189. * To slow it down, enter 1/600 for example.
  82190. * To speed it up, 1/30
  82191. * @param {number} newTimeStep the new timestep to apply to this world.
  82192. */
  82193. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82194. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82195. this._physicsPlugin.setTimeStep(newTimeStep);
  82196. };
  82197. /**
  82198. * Get the time step of the physics engine.
  82199. */
  82200. PhysicsEngine.prototype.getTimeStep = function () {
  82201. return this._physicsPlugin.getTimeStep();
  82202. };
  82203. PhysicsEngine.prototype.dispose = function () {
  82204. this._impostors.forEach(function (impostor) {
  82205. impostor.dispose();
  82206. });
  82207. this._physicsPlugin.dispose();
  82208. };
  82209. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82210. return this._physicsPlugin.name;
  82211. };
  82212. /**
  82213. * Adding a new impostor for the impostor tracking.
  82214. * This will be done by the impostor itself.
  82215. * @param {PhysicsImpostor} impostor the impostor to add
  82216. */
  82217. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82218. impostor.uniqueId = this._impostors.push(impostor);
  82219. //if no parent, generate the body
  82220. if (!impostor.parent) {
  82221. this._physicsPlugin.generatePhysicsBody(impostor);
  82222. }
  82223. };
  82224. /**
  82225. * Remove an impostor from the engine.
  82226. * This impostor and its mesh will not longer be updated by the physics engine.
  82227. * @param {PhysicsImpostor} impostor the impostor to remove
  82228. */
  82229. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82230. var index = this._impostors.indexOf(impostor);
  82231. if (index > -1) {
  82232. var removed = this._impostors.splice(index, 1);
  82233. //Is it needed?
  82234. if (removed.length) {
  82235. //this will also remove it from the world.
  82236. removed[0].physicsBody = null;
  82237. }
  82238. }
  82239. };
  82240. /**
  82241. * Add a joint to the physics engine
  82242. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82243. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82244. * @param {PhysicsJoint} the joint that will connect both impostors.
  82245. */
  82246. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82247. var impostorJoint = {
  82248. mainImpostor: mainImpostor,
  82249. connectedImpostor: connectedImpostor,
  82250. joint: joint
  82251. };
  82252. joint.physicsPlugin = this._physicsPlugin;
  82253. this._joints.push(impostorJoint);
  82254. this._physicsPlugin.generateJoint(impostorJoint);
  82255. };
  82256. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82257. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82258. return (impostorJoint.connectedImpostor === connectedImpostor
  82259. && impostorJoint.joint === joint
  82260. && impostorJoint.mainImpostor === mainImpostor);
  82261. });
  82262. if (matchingJoints.length) {
  82263. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82264. //TODO remove it from the list as well
  82265. }
  82266. };
  82267. /**
  82268. * Called by the scene. no need to call it.
  82269. */
  82270. PhysicsEngine.prototype._step = function (delta) {
  82271. var _this = this;
  82272. //check if any mesh has no body / requires an update
  82273. this._impostors.forEach(function (impostor) {
  82274. if (impostor.isBodyInitRequired()) {
  82275. _this._physicsPlugin.generatePhysicsBody(impostor);
  82276. }
  82277. });
  82278. if (delta > 0.1) {
  82279. delta = 0.1;
  82280. }
  82281. else if (delta <= 0) {
  82282. delta = 1.0 / 60.0;
  82283. }
  82284. this._physicsPlugin.executeStep(delta, this._impostors);
  82285. };
  82286. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82287. return this._physicsPlugin;
  82288. };
  82289. PhysicsEngine.prototype.getImpostors = function () {
  82290. return this._impostors;
  82291. };
  82292. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82293. for (var i = 0; i < this._impostors.length; ++i) {
  82294. if (this._impostors[i].object === object) {
  82295. return this._impostors[i];
  82296. }
  82297. }
  82298. return null;
  82299. };
  82300. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82301. for (var i = 0; i < this._impostors.length; ++i) {
  82302. if (this._impostors[i].physicsBody === body) {
  82303. return this._impostors[i];
  82304. }
  82305. }
  82306. return null;
  82307. };
  82308. // Statics
  82309. PhysicsEngine.Epsilon = 0.001;
  82310. return PhysicsEngine;
  82311. }());
  82312. BABYLON.PhysicsEngine = PhysicsEngine;
  82313. })(BABYLON || (BABYLON = {}));
  82314. //# sourceMappingURL=babylon.physicsEngine.js.map
  82315. var BABYLON;
  82316. (function (BABYLON) {
  82317. var PhysicsHelper = /** @class */ (function () {
  82318. function PhysicsHelper(scene) {
  82319. this._scene = scene;
  82320. this._physicsEngine = this._scene.getPhysicsEngine();
  82321. if (!this._physicsEngine) {
  82322. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82323. }
  82324. }
  82325. /**
  82326. * @param {Vector3} origin the origin of the explosion
  82327. * @param {number} radius the explosion radius
  82328. * @param {number} strength the explosion strength
  82329. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82330. */
  82331. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82332. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82333. if (!this._physicsEngine) {
  82334. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82335. return null;
  82336. }
  82337. var impostors = this._physicsEngine.getImpostors();
  82338. if (impostors.length === 0) {
  82339. return null;
  82340. }
  82341. var event = new PhysicsRadialExplosionEvent(this._scene);
  82342. impostors.forEach(function (impostor) {
  82343. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82344. if (!impostorForceAndContactPoint) {
  82345. return;
  82346. }
  82347. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82348. });
  82349. event.dispose(false);
  82350. return event;
  82351. };
  82352. /**
  82353. * @param {Vector3} origin the origin of the explosion
  82354. * @param {number} radius the explosion radius
  82355. * @param {number} strength the explosion strength
  82356. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82357. */
  82358. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82359. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82360. if (!this._physicsEngine) {
  82361. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82362. return null;
  82363. }
  82364. var impostors = this._physicsEngine.getImpostors();
  82365. if (impostors.length === 0) {
  82366. return null;
  82367. }
  82368. var event = new PhysicsRadialExplosionEvent(this._scene);
  82369. impostors.forEach(function (impostor) {
  82370. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82371. if (!impostorForceAndContactPoint) {
  82372. return;
  82373. }
  82374. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82375. });
  82376. event.dispose(false);
  82377. return event;
  82378. };
  82379. /**
  82380. * @param {Vector3} origin the origin of the explosion
  82381. * @param {number} radius the explosion radius
  82382. * @param {number} strength the explosion strength
  82383. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82384. */
  82385. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82386. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82387. if (!this._physicsEngine) {
  82388. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82389. return null;
  82390. }
  82391. var impostors = this._physicsEngine.getImpostors();
  82392. if (impostors.length === 0) {
  82393. return null;
  82394. }
  82395. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82396. event.dispose(false);
  82397. return event;
  82398. };
  82399. /**
  82400. * @param {Vector3} origin the origin of the updraft
  82401. * @param {number} radius the radius of the updraft
  82402. * @param {number} strength the strength of the updraft
  82403. * @param {number} height the height of the updraft
  82404. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82405. */
  82406. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82407. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82408. if (!this._physicsEngine) {
  82409. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82410. return null;
  82411. }
  82412. if (this._physicsEngine.getImpostors().length === 0) {
  82413. return null;
  82414. }
  82415. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82416. event.dispose(false);
  82417. return event;
  82418. };
  82419. /**
  82420. * @param {Vector3} origin the of the vortex
  82421. * @param {number} radius the radius of the vortex
  82422. * @param {number} strength the strength of the vortex
  82423. * @param {number} height the height of the vortex
  82424. */
  82425. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82426. if (!this._physicsEngine) {
  82427. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82428. return null;
  82429. }
  82430. if (this._physicsEngine.getImpostors().length === 0) {
  82431. return null;
  82432. }
  82433. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82434. event.dispose(false);
  82435. return event;
  82436. };
  82437. return PhysicsHelper;
  82438. }());
  82439. BABYLON.PhysicsHelper = PhysicsHelper;
  82440. /***** Radial explosion *****/
  82441. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82442. function PhysicsRadialExplosionEvent(scene) {
  82443. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82444. this._rays = [];
  82445. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82446. this._scene = scene;
  82447. }
  82448. /**
  82449. * Returns the data related to the radial explosion event (sphere & rays).
  82450. * @returns {PhysicsRadialExplosionEventData}
  82451. */
  82452. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82453. this._dataFetched = true;
  82454. return {
  82455. sphere: this._sphere,
  82456. rays: this._rays,
  82457. };
  82458. };
  82459. /**
  82460. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82461. * @param impostor
  82462. * @param {Vector3} origin the origin of the explosion
  82463. * @param {number} radius the explosion radius
  82464. * @param {number} strength the explosion strength
  82465. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82466. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82467. */
  82468. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82469. if (impostor.mass === 0) {
  82470. return null;
  82471. }
  82472. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82473. return null;
  82474. }
  82475. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82476. return null;
  82477. }
  82478. var impostorObjectCenter = impostor.getObjectCenter();
  82479. var direction = impostorObjectCenter.subtract(origin);
  82480. var ray = new BABYLON.Ray(origin, direction, radius);
  82481. this._rays.push(ray);
  82482. var hit = ray.intersectsMesh(impostor.object);
  82483. var contactPoint = hit.pickedPoint;
  82484. if (!contactPoint) {
  82485. return null;
  82486. }
  82487. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82488. if (distanceFromOrigin > radius) {
  82489. return null;
  82490. }
  82491. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82492. ? strength
  82493. : strength * (1 - (distanceFromOrigin / radius));
  82494. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82495. return { force: force, contactPoint: contactPoint };
  82496. };
  82497. /**
  82498. * Disposes the sphere.
  82499. * @param {bolean} force
  82500. */
  82501. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82502. var _this = this;
  82503. if (force === void 0) { force = true; }
  82504. if (force) {
  82505. this._sphere.dispose();
  82506. }
  82507. else {
  82508. setTimeout(function () {
  82509. if (!_this._dataFetched) {
  82510. _this._sphere.dispose();
  82511. }
  82512. }, 0);
  82513. }
  82514. };
  82515. /*** Helpers ***/
  82516. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82517. if (!this._sphere) {
  82518. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82519. this._sphere.isVisible = false;
  82520. }
  82521. };
  82522. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82523. var impostorObject = impostor.object;
  82524. this._prepareSphere();
  82525. this._sphere.position = origin;
  82526. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82527. this._sphere._updateBoundingInfo();
  82528. this._sphere.computeWorldMatrix(true);
  82529. return this._sphere.intersectsMesh(impostorObject, true);
  82530. };
  82531. return PhysicsRadialExplosionEvent;
  82532. }());
  82533. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82534. /***** Gravitational Field *****/
  82535. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82536. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82537. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82538. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82539. this._physicsHelper = physicsHelper;
  82540. this._scene = scene;
  82541. this._origin = origin;
  82542. this._radius = radius;
  82543. this._strength = strength;
  82544. this._falloff = falloff;
  82545. this._tickCallback = this._tick.bind(this);
  82546. }
  82547. /**
  82548. * Returns the data related to the gravitational field event (sphere).
  82549. * @returns {PhysicsGravitationalFieldEventData}
  82550. */
  82551. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82552. this._dataFetched = true;
  82553. return {
  82554. sphere: this._sphere,
  82555. };
  82556. };
  82557. /**
  82558. * Enables the gravitational field.
  82559. */
  82560. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82561. this._tickCallback.call(this);
  82562. this._scene.registerBeforeRender(this._tickCallback);
  82563. };
  82564. /**
  82565. * Disables the gravitational field.
  82566. */
  82567. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82568. this._scene.unregisterBeforeRender(this._tickCallback);
  82569. };
  82570. /**
  82571. * Disposes the sphere.
  82572. * @param {bolean} force
  82573. */
  82574. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82575. var _this = this;
  82576. if (force === void 0) { force = true; }
  82577. if (force) {
  82578. this._sphere.dispose();
  82579. }
  82580. else {
  82581. setTimeout(function () {
  82582. if (!_this._dataFetched) {
  82583. _this._sphere.dispose();
  82584. }
  82585. }, 0);
  82586. }
  82587. };
  82588. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82589. // Since the params won't change, we fetch the event only once
  82590. if (this._sphere) {
  82591. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82592. }
  82593. else {
  82594. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82595. if (radialExplosionEvent) {
  82596. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82597. }
  82598. }
  82599. };
  82600. return PhysicsGravitationalFieldEvent;
  82601. }());
  82602. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82603. /***** Updraft *****/
  82604. var PhysicsUpdraftEvent = /** @class */ (function () {
  82605. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82606. this._scene = _scene;
  82607. this._origin = _origin;
  82608. this._radius = _radius;
  82609. this._strength = _strength;
  82610. this._height = _height;
  82611. this._updraftMode = _updraftMode;
  82612. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82613. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82614. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82615. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82616. this._physicsEngine = this._scene.getPhysicsEngine();
  82617. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82618. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82619. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82620. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82621. }
  82622. this._tickCallback = this._tick.bind(this);
  82623. }
  82624. /**
  82625. * Returns the data related to the updraft event (cylinder).
  82626. * @returns {PhysicsUpdraftEventData}
  82627. */
  82628. PhysicsUpdraftEvent.prototype.getData = function () {
  82629. this._dataFetched = true;
  82630. return {
  82631. cylinder: this._cylinder,
  82632. };
  82633. };
  82634. /**
  82635. * Enables the updraft.
  82636. */
  82637. PhysicsUpdraftEvent.prototype.enable = function () {
  82638. this._tickCallback.call(this);
  82639. this._scene.registerBeforeRender(this._tickCallback);
  82640. };
  82641. /**
  82642. * Disables the cortex.
  82643. */
  82644. PhysicsUpdraftEvent.prototype.disable = function () {
  82645. this._scene.unregisterBeforeRender(this._tickCallback);
  82646. };
  82647. /**
  82648. * Disposes the sphere.
  82649. * @param {bolean} force
  82650. */
  82651. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82652. var _this = this;
  82653. if (force === void 0) { force = true; }
  82654. if (force) {
  82655. this._cylinder.dispose();
  82656. }
  82657. else {
  82658. setTimeout(function () {
  82659. if (!_this._dataFetched) {
  82660. _this._cylinder.dispose();
  82661. }
  82662. }, 0);
  82663. }
  82664. };
  82665. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82666. if (impostor.mass === 0) {
  82667. return null;
  82668. }
  82669. if (!this._intersectsWithCylinder(impostor)) {
  82670. return null;
  82671. }
  82672. var impostorObjectCenter = impostor.getObjectCenter();
  82673. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82674. var direction = this._originDirection;
  82675. }
  82676. else {
  82677. var direction = impostorObjectCenter.subtract(this._originTop);
  82678. }
  82679. var multiplier = this._strength * -1;
  82680. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82681. return { force: force, contactPoint: impostorObjectCenter };
  82682. };
  82683. PhysicsUpdraftEvent.prototype._tick = function () {
  82684. var _this = this;
  82685. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82686. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82687. if (!impostorForceAndContactPoint) {
  82688. return;
  82689. }
  82690. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82691. });
  82692. };
  82693. /*** Helpers ***/
  82694. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82695. if (!this._cylinder) {
  82696. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82697. height: this._height,
  82698. diameter: this._radius * 2,
  82699. }, this._scene);
  82700. this._cylinder.isVisible = false;
  82701. }
  82702. };
  82703. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82704. var impostorObject = impostor.object;
  82705. this._prepareCylinder();
  82706. this._cylinder.position = this._cylinderPosition;
  82707. return this._cylinder.intersectsMesh(impostorObject, true);
  82708. };
  82709. return PhysicsUpdraftEvent;
  82710. }());
  82711. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82712. /***** Vortex *****/
  82713. var PhysicsVortexEvent = /** @class */ (function () {
  82714. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82715. this._scene = _scene;
  82716. this._origin = _origin;
  82717. this._radius = _radius;
  82718. this._strength = _strength;
  82719. this._height = _height;
  82720. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82721. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82722. this._updraftMultiplier = 0.02;
  82723. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82724. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82725. this._physicsEngine = this._scene.getPhysicsEngine();
  82726. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82727. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82728. this._tickCallback = this._tick.bind(this);
  82729. }
  82730. /**
  82731. * Returns the data related to the vortex event (cylinder).
  82732. * @returns {PhysicsVortexEventData}
  82733. */
  82734. PhysicsVortexEvent.prototype.getData = function () {
  82735. this._dataFetched = true;
  82736. return {
  82737. cylinder: this._cylinder,
  82738. };
  82739. };
  82740. /**
  82741. * Enables the vortex.
  82742. */
  82743. PhysicsVortexEvent.prototype.enable = function () {
  82744. this._tickCallback.call(this);
  82745. this._scene.registerBeforeRender(this._tickCallback);
  82746. };
  82747. /**
  82748. * Disables the cortex.
  82749. */
  82750. PhysicsVortexEvent.prototype.disable = function () {
  82751. this._scene.unregisterBeforeRender(this._tickCallback);
  82752. };
  82753. /**
  82754. * Disposes the sphere.
  82755. * @param {bolean} force
  82756. */
  82757. PhysicsVortexEvent.prototype.dispose = function (force) {
  82758. var _this = this;
  82759. if (force === void 0) { force = true; }
  82760. if (force) {
  82761. this._cylinder.dispose();
  82762. }
  82763. else {
  82764. setTimeout(function () {
  82765. if (!_this._dataFetched) {
  82766. _this._cylinder.dispose();
  82767. }
  82768. }, 0);
  82769. }
  82770. };
  82771. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82772. if (impostor.mass === 0) {
  82773. return null;
  82774. }
  82775. if (!this._intersectsWithCylinder(impostor)) {
  82776. return null;
  82777. }
  82778. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82779. return null;
  82780. }
  82781. var impostorObjectCenter = impostor.getObjectCenter();
  82782. 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)
  82783. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82784. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82785. var hit = ray.intersectsMesh(impostor.object);
  82786. var contactPoint = hit.pickedPoint;
  82787. if (!contactPoint) {
  82788. return null;
  82789. }
  82790. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82791. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82792. var directionToOrigin = contactPoint.normalize();
  82793. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82794. directionToOrigin = directionToOrigin.negate();
  82795. }
  82796. // TODO: find a more physically based solution
  82797. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82798. var forceX = directionToOrigin.x * this._strength / 8;
  82799. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82800. var forceZ = directionToOrigin.z * this._strength / 8;
  82801. }
  82802. else {
  82803. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82804. var forceY = this._originTop.y * this._updraftMultiplier;
  82805. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82806. }
  82807. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82808. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82809. return { force: force, contactPoint: impostorObjectCenter };
  82810. };
  82811. PhysicsVortexEvent.prototype._tick = function () {
  82812. var _this = this;
  82813. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82814. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82815. if (!impostorForceAndContactPoint) {
  82816. return;
  82817. }
  82818. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82819. });
  82820. };
  82821. /*** Helpers ***/
  82822. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82823. if (!this._cylinder) {
  82824. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82825. height: this._height,
  82826. diameter: this._radius * 2,
  82827. }, this._scene);
  82828. this._cylinder.isVisible = false;
  82829. }
  82830. };
  82831. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82832. var impostorObject = impostor.object;
  82833. this._prepareCylinder();
  82834. this._cylinder.position = this._cylinderPosition;
  82835. return this._cylinder.intersectsMesh(impostorObject, true);
  82836. };
  82837. return PhysicsVortexEvent;
  82838. }());
  82839. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82840. /***** Enums *****/
  82841. /**
  82842. * The strenght of the force in correspondence to the distance of the affected object
  82843. */
  82844. var PhysicsRadialImpulseFalloff;
  82845. (function (PhysicsRadialImpulseFalloff) {
  82846. /** Defines that impulse is constant in strength across it's whole radius */
  82847. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82848. /** DEfines that impulse gets weaker if it's further from the origin */
  82849. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82850. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82851. /**
  82852. * The strenght of the force in correspondence to the distance of the affected object
  82853. */
  82854. var PhysicsUpdraftMode;
  82855. (function (PhysicsUpdraftMode) {
  82856. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82857. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82858. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82859. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82860. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82861. })(BABYLON || (BABYLON = {}));
  82862. //# sourceMappingURL=babylon.physicsHelper.js.map
  82863. var BABYLON;
  82864. (function (BABYLON) {
  82865. var CannonJSPlugin = /** @class */ (function () {
  82866. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82867. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82868. if (iterations === void 0) { iterations = 10; }
  82869. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82870. this.name = "CannonJSPlugin";
  82871. this._physicsMaterials = new Array();
  82872. this._fixedTimeStep = 1 / 60;
  82873. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82874. this.BJSCANNON = CANNON;
  82875. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82876. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82877. this._tmpPosition = BABYLON.Vector3.Zero();
  82878. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82879. this._tmpUnityRotation = new BABYLON.Quaternion();
  82880. if (!this.isSupported()) {
  82881. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82882. return;
  82883. }
  82884. this._extendNamespace();
  82885. this.world = new this.BJSCANNON.World();
  82886. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82887. this.world.solver.iterations = iterations;
  82888. }
  82889. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82890. this.world.gravity.copy(gravity);
  82891. };
  82892. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82893. this._fixedTimeStep = timeStep;
  82894. };
  82895. CannonJSPlugin.prototype.getTimeStep = function () {
  82896. return this._fixedTimeStep;
  82897. };
  82898. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82899. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82900. };
  82901. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82902. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82903. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82904. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82905. };
  82906. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82907. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82908. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82909. impostor.physicsBody.applyForce(impulse, worldPoint);
  82910. };
  82911. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82912. //parent-child relationship. Does this impostor has a parent impostor?
  82913. if (impostor.parent) {
  82914. if (impostor.physicsBody) {
  82915. this.removePhysicsBody(impostor);
  82916. //TODO is that needed?
  82917. impostor.forceUpdate();
  82918. }
  82919. return;
  82920. }
  82921. //should a new body be created for this impostor?
  82922. if (impostor.isBodyInitRequired()) {
  82923. var shape = this._createShape(impostor);
  82924. //unregister events, if body is being changed
  82925. var oldBody = impostor.physicsBody;
  82926. if (oldBody) {
  82927. this.removePhysicsBody(impostor);
  82928. }
  82929. //create the body and material
  82930. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82931. var bodyCreationObject = {
  82932. mass: impostor.getParam("mass"),
  82933. material: material
  82934. };
  82935. // A simple extend, in case native options were used.
  82936. var nativeOptions = impostor.getParam("nativeOptions");
  82937. for (var key in nativeOptions) {
  82938. if (nativeOptions.hasOwnProperty(key)) {
  82939. bodyCreationObject[key] = nativeOptions[key];
  82940. }
  82941. }
  82942. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  82943. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  82944. this.world.addEventListener("preStep", impostor.beforeStep);
  82945. this.world.addEventListener("postStep", impostor.afterStep);
  82946. impostor.physicsBody.addShape(shape);
  82947. this.world.add(impostor.physicsBody);
  82948. //try to keep the body moving in the right direction by taking old properties.
  82949. //Should be tested!
  82950. if (oldBody) {
  82951. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  82952. impostor.physicsBody[param].copy(oldBody[param]);
  82953. });
  82954. }
  82955. this._processChildMeshes(impostor);
  82956. }
  82957. //now update the body's transformation
  82958. this._updatePhysicsBodyTransformation(impostor);
  82959. };
  82960. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  82961. var _this = this;
  82962. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  82963. var currentRotation = mainImpostor.object.rotationQuaternion;
  82964. if (meshChildren.length) {
  82965. var processMesh = function (localPosition, mesh) {
  82966. if (!currentRotation || !mesh.rotationQuaternion) {
  82967. return;
  82968. }
  82969. var childImpostor = mesh.getPhysicsImpostor();
  82970. if (childImpostor) {
  82971. var parent = childImpostor.parent;
  82972. if (parent !== mainImpostor) {
  82973. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  82974. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  82975. if (childImpostor.physicsBody) {
  82976. _this.removePhysicsBody(childImpostor);
  82977. childImpostor.physicsBody = null;
  82978. }
  82979. childImpostor.parent = mainImpostor;
  82980. childImpostor.resetUpdateFlags();
  82981. 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));
  82982. //Add the mass of the children.
  82983. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  82984. }
  82985. }
  82986. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  82987. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  82988. };
  82989. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  82990. }
  82991. };
  82992. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82993. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  82994. this.world.removeEventListener("preStep", impostor.beforeStep);
  82995. this.world.removeEventListener("postStep", impostor.afterStep);
  82996. this.world.remove(impostor.physicsBody);
  82997. };
  82998. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82999. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83000. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83001. if (!mainBody || !connectedBody) {
  83002. return;
  83003. }
  83004. var constraint;
  83005. var jointData = impostorJoint.joint.jointData;
  83006. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83007. var constraintData = {
  83008. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83009. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83010. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83011. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83012. maxForce: jointData.nativeParams.maxForce,
  83013. collideConnected: !!jointData.collision
  83014. };
  83015. switch (impostorJoint.joint.type) {
  83016. case BABYLON.PhysicsJoint.HingeJoint:
  83017. case BABYLON.PhysicsJoint.Hinge2Joint:
  83018. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83019. break;
  83020. case BABYLON.PhysicsJoint.DistanceJoint:
  83021. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83022. break;
  83023. case BABYLON.PhysicsJoint.SpringJoint:
  83024. var springData = jointData;
  83025. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83026. restLength: springData.length,
  83027. stiffness: springData.stiffness,
  83028. damping: springData.damping,
  83029. localAnchorA: constraintData.pivotA,
  83030. localAnchorB: constraintData.pivotB
  83031. });
  83032. break;
  83033. case BABYLON.PhysicsJoint.LockJoint:
  83034. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83035. break;
  83036. case BABYLON.PhysicsJoint.PointToPointJoint:
  83037. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83038. default:
  83039. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83040. break;
  83041. }
  83042. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83043. constraint.collideConnected = !!jointData.collision;
  83044. impostorJoint.joint.physicsJoint = constraint;
  83045. //don't add spring as constraint, as it is not one.
  83046. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83047. this.world.addConstraint(constraint);
  83048. }
  83049. else {
  83050. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83051. constraint.applyForce();
  83052. });
  83053. }
  83054. };
  83055. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83056. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83057. };
  83058. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83059. var index;
  83060. var mat;
  83061. for (index = 0; index < this._physicsMaterials.length; index++) {
  83062. mat = this._physicsMaterials[index];
  83063. if (mat.friction === friction && mat.restitution === restitution) {
  83064. return mat;
  83065. }
  83066. }
  83067. var currentMat = new this.BJSCANNON.Material(name);
  83068. currentMat.friction = friction;
  83069. currentMat.restitution = restitution;
  83070. this._physicsMaterials.push(currentMat);
  83071. return currentMat;
  83072. };
  83073. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83074. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83075. };
  83076. CannonJSPlugin.prototype._createShape = function (impostor) {
  83077. var object = impostor.object;
  83078. var returnValue;
  83079. var extendSize = impostor.getObjectExtendSize();
  83080. switch (impostor.type) {
  83081. case BABYLON.PhysicsImpostor.SphereImpostor:
  83082. var radiusX = extendSize.x;
  83083. var radiusY = extendSize.y;
  83084. var radiusZ = extendSize.z;
  83085. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83086. break;
  83087. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83088. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83089. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83090. break;
  83091. case BABYLON.PhysicsImpostor.BoxImpostor:
  83092. var box = extendSize.scale(0.5);
  83093. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83094. break;
  83095. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83096. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83097. returnValue = new this.BJSCANNON.Plane();
  83098. break;
  83099. case BABYLON.PhysicsImpostor.MeshImpostor:
  83100. // should transform the vertex data to world coordinates!!
  83101. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83102. var rawFaces = object.getIndices ? object.getIndices() : [];
  83103. if (!rawVerts)
  83104. return;
  83105. // get only scale! so the object could transform correctly.
  83106. var oldPosition = object.position.clone();
  83107. var oldRotation = object.rotation && object.rotation.clone();
  83108. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83109. object.position.copyFromFloats(0, 0, 0);
  83110. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83111. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83112. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83113. var transform = object.computeWorldMatrix(true);
  83114. // convert rawVerts to object space
  83115. var temp = new Array();
  83116. var index;
  83117. for (index = 0; index < rawVerts.length; index += 3) {
  83118. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83119. }
  83120. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83121. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83122. //now set back the transformation!
  83123. object.position.copyFrom(oldPosition);
  83124. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83125. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83126. break;
  83127. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83128. var oldPosition2 = object.position.clone();
  83129. var oldRotation2 = object.rotation && object.rotation.clone();
  83130. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83131. object.position.copyFromFloats(0, 0, 0);
  83132. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83133. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83134. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83135. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83136. returnValue = this._createHeightmap(object);
  83137. object.position.copyFrom(oldPosition2);
  83138. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83139. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83140. object.computeWorldMatrix(true);
  83141. break;
  83142. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83143. returnValue = new this.BJSCANNON.Particle();
  83144. break;
  83145. }
  83146. return returnValue;
  83147. };
  83148. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83149. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83150. var transform = object.computeWorldMatrix(true);
  83151. // convert rawVerts to object space
  83152. var temp = new Array();
  83153. var index;
  83154. for (index = 0; index < pos.length; index += 3) {
  83155. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83156. }
  83157. pos = temp;
  83158. var matrix = new Array();
  83159. //For now pointDepth will not be used and will be automatically calculated.
  83160. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83161. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83162. var boundingInfo = object.getBoundingInfo();
  83163. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83164. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83165. var elementSize = dim * 2 / arraySize;
  83166. for (var i = 0; i < pos.length; i = i + 3) {
  83167. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83168. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83169. var y = -pos[i + 2] + minY;
  83170. if (!matrix[x]) {
  83171. matrix[x] = [];
  83172. }
  83173. if (!matrix[x][z]) {
  83174. matrix[x][z] = y;
  83175. }
  83176. matrix[x][z] = Math.max(y, matrix[x][z]);
  83177. }
  83178. for (var x = 0; x <= arraySize; ++x) {
  83179. if (!matrix[x]) {
  83180. var loc = 1;
  83181. while (!matrix[(x + loc) % arraySize]) {
  83182. loc++;
  83183. }
  83184. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83185. //console.log("missing x", x);
  83186. }
  83187. for (var z = 0; z <= arraySize; ++z) {
  83188. if (!matrix[x][z]) {
  83189. var loc = 1;
  83190. var newValue;
  83191. while (newValue === undefined) {
  83192. newValue = matrix[x][(z + loc++) % arraySize];
  83193. }
  83194. matrix[x][z] = newValue;
  83195. }
  83196. }
  83197. }
  83198. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83199. elementSize: elementSize
  83200. });
  83201. //For future reference, needed for body transformation
  83202. shape.minY = minY;
  83203. return shape;
  83204. };
  83205. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83206. var object = impostor.object;
  83207. //make sure it is updated...
  83208. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83209. // The delta between the mesh position and the mesh bounding box center
  83210. var bInfo = object.getBoundingInfo();
  83211. if (!bInfo)
  83212. return;
  83213. var center = impostor.getObjectCenter();
  83214. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83215. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83216. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83217. this._tmpPosition.copyFrom(center);
  83218. var quaternion = object.rotationQuaternion;
  83219. if (!quaternion) {
  83220. return;
  83221. }
  83222. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83223. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83224. //-90 DEG in X, precalculated
  83225. quaternion = quaternion.multiply(this._minus90X);
  83226. //Invert! (Precalculated, 90 deg in X)
  83227. //No need to clone. this will never change.
  83228. impostor.setDeltaRotation(this._plus90X);
  83229. }
  83230. //If it is a heightfield, if should be centered.
  83231. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83232. var mesh = object;
  83233. var boundingInfo = mesh.getBoundingInfo();
  83234. //calculate the correct body position:
  83235. var rotationQuaternion = mesh.rotationQuaternion;
  83236. mesh.rotationQuaternion = this._tmpUnityRotation;
  83237. mesh.computeWorldMatrix(true);
  83238. //get original center with no rotation
  83239. var c = center.clone();
  83240. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83241. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83242. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83243. mesh.setPreTransformMatrix(p);
  83244. mesh.computeWorldMatrix(true);
  83245. //calculate the translation
  83246. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83247. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83248. //add it inverted to the delta
  83249. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83250. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83251. //rotation is back
  83252. mesh.rotationQuaternion = rotationQuaternion;
  83253. mesh.setPreTransformMatrix(oldPivot);
  83254. mesh.computeWorldMatrix(true);
  83255. }
  83256. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83257. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83258. //this._tmpPosition.copyFrom(object.position);
  83259. }
  83260. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83261. //Now update the impostor object
  83262. impostor.physicsBody.position.copy(this._tmpPosition);
  83263. impostor.physicsBody.quaternion.copy(quaternion);
  83264. };
  83265. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83266. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83267. if (impostor.object.rotationQuaternion) {
  83268. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83269. }
  83270. };
  83271. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83272. impostor.physicsBody.position.copy(newPosition);
  83273. impostor.physicsBody.quaternion.copy(newRotation);
  83274. };
  83275. CannonJSPlugin.prototype.isSupported = function () {
  83276. return this.BJSCANNON !== undefined;
  83277. };
  83278. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83279. impostor.physicsBody.velocity.copy(velocity);
  83280. };
  83281. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83282. impostor.physicsBody.angularVelocity.copy(velocity);
  83283. };
  83284. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83285. var v = impostor.physicsBody.velocity;
  83286. if (!v) {
  83287. return null;
  83288. }
  83289. return new BABYLON.Vector3(v.x, v.y, v.z);
  83290. };
  83291. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83292. var v = impostor.physicsBody.angularVelocity;
  83293. if (!v) {
  83294. return null;
  83295. }
  83296. return new BABYLON.Vector3(v.x, v.y, v.z);
  83297. };
  83298. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83299. impostor.physicsBody.mass = mass;
  83300. impostor.physicsBody.updateMassProperties();
  83301. };
  83302. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83303. return impostor.physicsBody.mass;
  83304. };
  83305. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83306. return impostor.physicsBody.material.friction;
  83307. };
  83308. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83309. impostor.physicsBody.material.friction = friction;
  83310. };
  83311. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83312. return impostor.physicsBody.material.restitution;
  83313. };
  83314. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83315. impostor.physicsBody.material.restitution = restitution;
  83316. };
  83317. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83318. impostor.physicsBody.sleep();
  83319. };
  83320. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83321. impostor.physicsBody.wakeUp();
  83322. };
  83323. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83324. joint.physicsJoint.distance = maxDistance;
  83325. };
  83326. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83327. // if (!motorIndex) {
  83328. // joint.physicsJoint.enableMotor();
  83329. // }
  83330. // }
  83331. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83332. // if (!motorIndex) {
  83333. // joint.physicsJoint.disableMotor();
  83334. // }
  83335. // }
  83336. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83337. if (!motorIndex) {
  83338. joint.physicsJoint.enableMotor();
  83339. joint.physicsJoint.setMotorSpeed(speed);
  83340. if (maxForce) {
  83341. this.setLimit(joint, maxForce);
  83342. }
  83343. }
  83344. };
  83345. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83346. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83347. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83348. };
  83349. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83350. var body = impostor.physicsBody;
  83351. mesh.position.x = body.position.x;
  83352. mesh.position.y = body.position.y;
  83353. mesh.position.z = body.position.z;
  83354. if (mesh.rotationQuaternion) {
  83355. mesh.rotationQuaternion.x = body.quaternion.x;
  83356. mesh.rotationQuaternion.y = body.quaternion.y;
  83357. mesh.rotationQuaternion.z = body.quaternion.z;
  83358. mesh.rotationQuaternion.w = body.quaternion.w;
  83359. }
  83360. };
  83361. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83362. var shape = impostor.physicsBody.shapes[0];
  83363. return shape.boundingSphereRadius;
  83364. };
  83365. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83366. var shape = impostor.physicsBody.shapes[0];
  83367. result.x = shape.halfExtents.x * 2;
  83368. result.y = shape.halfExtents.y * 2;
  83369. result.z = shape.halfExtents.z * 2;
  83370. };
  83371. CannonJSPlugin.prototype.dispose = function () {
  83372. };
  83373. CannonJSPlugin.prototype._extendNamespace = function () {
  83374. //this will force cannon to execute at least one step when using interpolation
  83375. var step_tmp1 = new this.BJSCANNON.Vec3();
  83376. var Engine = this.BJSCANNON;
  83377. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83378. maxSubSteps = maxSubSteps || 10;
  83379. timeSinceLastCalled = timeSinceLastCalled || 0;
  83380. if (timeSinceLastCalled === 0) {
  83381. this.internalStep(dt);
  83382. this.time += dt;
  83383. }
  83384. else {
  83385. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83386. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83387. var t0 = performance.now();
  83388. for (var i = 0; i !== internalSteps; i++) {
  83389. this.internalStep(dt);
  83390. if (performance.now() - t0 > dt * 1000) {
  83391. break;
  83392. }
  83393. }
  83394. this.time += timeSinceLastCalled;
  83395. var h = this.time % dt;
  83396. var h_div_dt = h / dt;
  83397. var interpvelo = step_tmp1;
  83398. var bodies = this.bodies;
  83399. for (var j = 0; j !== bodies.length; j++) {
  83400. var b = bodies[j];
  83401. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83402. b.position.vsub(b.previousPosition, interpvelo);
  83403. interpvelo.scale(h_div_dt, interpvelo);
  83404. b.position.vadd(interpvelo, b.interpolatedPosition);
  83405. }
  83406. else {
  83407. b.interpolatedPosition.copy(b.position);
  83408. b.interpolatedQuaternion.copy(b.quaternion);
  83409. }
  83410. }
  83411. }
  83412. };
  83413. };
  83414. return CannonJSPlugin;
  83415. }());
  83416. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83417. })(BABYLON || (BABYLON = {}));
  83418. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83419. var BABYLON;
  83420. (function (BABYLON) {
  83421. var OimoJSPlugin = /** @class */ (function () {
  83422. function OimoJSPlugin(iterations) {
  83423. this.name = "OimoJSPlugin";
  83424. this._tmpImpostorsArray = [];
  83425. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83426. this.BJSOIMO = OIMO;
  83427. this.world = new this.BJSOIMO.World({
  83428. iterations: iterations
  83429. });
  83430. this.world.clear();
  83431. }
  83432. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83433. this.world.gravity.copy(gravity);
  83434. };
  83435. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83436. this.world.timeStep = timeStep;
  83437. };
  83438. OimoJSPlugin.prototype.getTimeStep = function () {
  83439. return this.world.timeStep;
  83440. };
  83441. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83442. var _this = this;
  83443. impostors.forEach(function (impostor) {
  83444. impostor.beforeStep();
  83445. });
  83446. this.world.step();
  83447. impostors.forEach(function (impostor) {
  83448. impostor.afterStep();
  83449. //update the ordered impostors array
  83450. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83451. });
  83452. //check for collisions
  83453. var contact = this.world.contacts;
  83454. while (contact !== null) {
  83455. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83456. contact = contact.next;
  83457. continue;
  83458. }
  83459. //is this body colliding with any other? get the impostor
  83460. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83461. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83462. if (!mainImpostor || !collidingImpostor) {
  83463. contact = contact.next;
  83464. continue;
  83465. }
  83466. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83467. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83468. contact = contact.next;
  83469. }
  83470. };
  83471. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83472. var mass = impostor.physicsBody.mass;
  83473. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83474. };
  83475. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83476. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83477. this.applyImpulse(impostor, force, contactPoint);
  83478. };
  83479. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83480. var _this = this;
  83481. //parent-child relationship. Does this impostor has a parent impostor?
  83482. if (impostor.parent) {
  83483. if (impostor.physicsBody) {
  83484. this.removePhysicsBody(impostor);
  83485. //TODO is that needed?
  83486. impostor.forceUpdate();
  83487. }
  83488. return;
  83489. }
  83490. if (impostor.isBodyInitRequired()) {
  83491. var bodyConfig = {
  83492. name: impostor.uniqueId,
  83493. //Oimo must have mass, also for static objects.
  83494. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83495. size: [],
  83496. type: [],
  83497. pos: [],
  83498. posShape: [],
  83499. rot: [],
  83500. rotShape: [],
  83501. move: impostor.getParam("mass") !== 0,
  83502. density: impostor.getParam("mass"),
  83503. friction: impostor.getParam("friction"),
  83504. restitution: impostor.getParam("restitution"),
  83505. //Supporting older versions of Oimo
  83506. world: this.world
  83507. };
  83508. var impostors = [impostor];
  83509. var addToArray = function (parent) {
  83510. if (!parent.getChildMeshes)
  83511. return;
  83512. parent.getChildMeshes().forEach(function (m) {
  83513. if (m.physicsImpostor) {
  83514. impostors.push(m.physicsImpostor);
  83515. //m.physicsImpostor._init();
  83516. }
  83517. });
  83518. };
  83519. addToArray(impostor.object);
  83520. var checkWithEpsilon_1 = function (value) {
  83521. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83522. };
  83523. impostors.forEach(function (i) {
  83524. if (!i.object.rotationQuaternion) {
  83525. return;
  83526. }
  83527. //get the correct bounding box
  83528. var oldQuaternion = i.object.rotationQuaternion;
  83529. var rot = oldQuaternion.toEulerAngles();
  83530. var extendSize = i.getObjectExtendSize();
  83531. var radToDeg = 57.295779513082320876;
  83532. if (i === impostor) {
  83533. var center = impostor.getObjectCenter();
  83534. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83535. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83536. //Can also use Array.prototype.push.apply
  83537. bodyConfig.pos.push(center.x);
  83538. bodyConfig.pos.push(center.y);
  83539. bodyConfig.pos.push(center.z);
  83540. bodyConfig.posShape.push(0, 0, 0);
  83541. //tmp solution
  83542. bodyConfig.rot.push(rot.x * radToDeg);
  83543. bodyConfig.rot.push(rot.y * radToDeg);
  83544. bodyConfig.rot.push(rot.z * radToDeg);
  83545. bodyConfig.rotShape.push(0, 0, 0);
  83546. }
  83547. else {
  83548. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83549. bodyConfig.posShape.push(localPosition.x);
  83550. bodyConfig.posShape.push(localPosition.y);
  83551. bodyConfig.posShape.push(localPosition.z);
  83552. bodyConfig.pos.push(0, 0, 0);
  83553. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83554. bodyConfig.rot.push(0);
  83555. bodyConfig.rot.push(0);
  83556. bodyConfig.rot.push(0);
  83557. bodyConfig.rotShape.push(rot.x * radToDeg);
  83558. bodyConfig.rotShape.push(rot.y * radToDeg);
  83559. bodyConfig.rotShape.push(rot.z * radToDeg);
  83560. }
  83561. // register mesh
  83562. switch (i.type) {
  83563. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83564. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83565. case BABYLON.PhysicsImpostor.SphereImpostor:
  83566. var radiusX = extendSize.x;
  83567. var radiusY = extendSize.y;
  83568. var radiusZ = extendSize.z;
  83569. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83570. bodyConfig.type.push('sphere');
  83571. //due to the way oimo works with compounds, add 3 times
  83572. bodyConfig.size.push(size);
  83573. bodyConfig.size.push(size);
  83574. bodyConfig.size.push(size);
  83575. break;
  83576. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83577. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83578. var sizeY = checkWithEpsilon_1(extendSize.y);
  83579. bodyConfig.type.push('cylinder');
  83580. bodyConfig.size.push(sizeX);
  83581. bodyConfig.size.push(sizeY);
  83582. //due to the way oimo works with compounds, add one more value.
  83583. bodyConfig.size.push(sizeY);
  83584. break;
  83585. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83586. case BABYLON.PhysicsImpostor.BoxImpostor:
  83587. default:
  83588. var sizeX = checkWithEpsilon_1(extendSize.x);
  83589. var sizeY = checkWithEpsilon_1(extendSize.y);
  83590. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83591. bodyConfig.type.push('box');
  83592. //if (i === impostor) {
  83593. bodyConfig.size.push(sizeX);
  83594. bodyConfig.size.push(sizeY);
  83595. bodyConfig.size.push(sizeZ);
  83596. //} else {
  83597. // bodyConfig.size.push(0,0,0);
  83598. //}
  83599. break;
  83600. }
  83601. //actually not needed, but hey...
  83602. i.object.rotationQuaternion = oldQuaternion;
  83603. });
  83604. impostor.physicsBody = this.world.add(bodyConfig);
  83605. }
  83606. else {
  83607. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83608. }
  83609. impostor.setDeltaPosition(this._tmpPositionVector);
  83610. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83611. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83612. };
  83613. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83614. //impostor.physicsBody.dispose();
  83615. //Same as : (older oimo versions)
  83616. this.world.removeRigidBody(impostor.physicsBody);
  83617. };
  83618. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83619. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83620. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83621. if (!mainBody || !connectedBody) {
  83622. return;
  83623. }
  83624. var jointData = impostorJoint.joint.jointData;
  83625. var options = jointData.nativeParams || {};
  83626. var type;
  83627. var nativeJointData = {
  83628. body1: mainBody,
  83629. body2: connectedBody,
  83630. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83631. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83632. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83633. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83634. min: options.min,
  83635. max: options.max,
  83636. collision: options.collision || jointData.collision,
  83637. spring: options.spring,
  83638. //supporting older version of Oimo
  83639. world: this.world
  83640. };
  83641. switch (impostorJoint.joint.type) {
  83642. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83643. type = "jointBall";
  83644. break;
  83645. case BABYLON.PhysicsJoint.SpringJoint:
  83646. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83647. var springData = jointData;
  83648. nativeJointData.min = springData.length || nativeJointData.min;
  83649. //Max should also be set, just make sure it is at least min
  83650. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83651. case BABYLON.PhysicsJoint.DistanceJoint:
  83652. type = "jointDistance";
  83653. nativeJointData.max = jointData.maxDistance;
  83654. break;
  83655. case BABYLON.PhysicsJoint.PrismaticJoint:
  83656. type = "jointPrisme";
  83657. break;
  83658. case BABYLON.PhysicsJoint.SliderJoint:
  83659. type = "jointSlide";
  83660. break;
  83661. case BABYLON.PhysicsJoint.WheelJoint:
  83662. type = "jointWheel";
  83663. break;
  83664. case BABYLON.PhysicsJoint.HingeJoint:
  83665. default:
  83666. type = "jointHinge";
  83667. break;
  83668. }
  83669. nativeJointData.type = type;
  83670. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83671. };
  83672. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83673. //Bug in Oimo prevents us from disposing a joint in the playground
  83674. //joint.joint.physicsJoint.dispose();
  83675. //So we will bruteforce it!
  83676. try {
  83677. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83678. }
  83679. catch (e) {
  83680. BABYLON.Tools.Warn(e);
  83681. }
  83682. };
  83683. OimoJSPlugin.prototype.isSupported = function () {
  83684. return this.BJSOIMO !== undefined;
  83685. };
  83686. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83687. if (!impostor.physicsBody.sleeping) {
  83688. //TODO check that
  83689. /*if (impostor.physicsBody.shapes.next) {
  83690. var parentShape = this._getLastShape(impostor.physicsBody);
  83691. impostor.object.position.copyFrom(parentShape.position);
  83692. console.log(parentShape.position);
  83693. } else {*/
  83694. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83695. //}
  83696. if (impostor.object.rotationQuaternion) {
  83697. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83698. }
  83699. }
  83700. };
  83701. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83702. var body = impostor.physicsBody;
  83703. body.position.copy(newPosition);
  83704. body.orientation.copy(newRotation);
  83705. body.syncShapes();
  83706. body.awake();
  83707. };
  83708. /*private _getLastShape(body: any): any {
  83709. var lastShape = body.shapes;
  83710. while (lastShape.next) {
  83711. lastShape = lastShape.next;
  83712. }
  83713. return lastShape;
  83714. }*/
  83715. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83716. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83717. };
  83718. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83719. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83720. };
  83721. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83722. var v = impostor.physicsBody.linearVelocity;
  83723. if (!v) {
  83724. return null;
  83725. }
  83726. return new BABYLON.Vector3(v.x, v.y, v.z);
  83727. };
  83728. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83729. var v = impostor.physicsBody.angularVelocity;
  83730. if (!v) {
  83731. return null;
  83732. }
  83733. return new BABYLON.Vector3(v.x, v.y, v.z);
  83734. };
  83735. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83736. var staticBody = mass === 0;
  83737. //this will actually set the body's density and not its mass.
  83738. //But this is how oimo treats the mass variable.
  83739. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83740. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83741. };
  83742. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83743. return impostor.physicsBody.shapes.density;
  83744. };
  83745. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83746. return impostor.physicsBody.shapes.friction;
  83747. };
  83748. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83749. impostor.physicsBody.shapes.friction = friction;
  83750. };
  83751. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83752. return impostor.physicsBody.shapes.restitution;
  83753. };
  83754. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83755. impostor.physicsBody.shapes.restitution = restitution;
  83756. };
  83757. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83758. impostor.physicsBody.sleep();
  83759. };
  83760. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83761. impostor.physicsBody.awake();
  83762. };
  83763. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83764. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83765. if (minDistance !== void 0) {
  83766. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83767. }
  83768. };
  83769. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83770. //TODO separate rotational and transational motors.
  83771. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83772. if (motor) {
  83773. motor.setMotor(speed, maxForce);
  83774. }
  83775. };
  83776. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83777. //TODO separate rotational and transational motors.
  83778. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83779. if (motor) {
  83780. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83781. }
  83782. };
  83783. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83784. var body = impostor.physicsBody;
  83785. mesh.position.x = body.position.x;
  83786. mesh.position.y = body.position.y;
  83787. mesh.position.z = body.position.z;
  83788. if (mesh.rotationQuaternion) {
  83789. mesh.rotationQuaternion.x = body.orientation.x;
  83790. mesh.rotationQuaternion.y = body.orientation.y;
  83791. mesh.rotationQuaternion.z = body.orientation.z;
  83792. mesh.rotationQuaternion.w = body.orientation.s;
  83793. }
  83794. };
  83795. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83796. return impostor.physicsBody.shapes.radius;
  83797. };
  83798. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83799. var shape = impostor.physicsBody.shapes;
  83800. result.x = shape.halfWidth * 2;
  83801. result.y = shape.halfHeight * 2;
  83802. result.z = shape.halfDepth * 2;
  83803. };
  83804. OimoJSPlugin.prototype.dispose = function () {
  83805. this.world.clear();
  83806. };
  83807. return OimoJSPlugin;
  83808. }());
  83809. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83810. })(BABYLON || (BABYLON = {}));
  83811. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83812. var BABYLON;
  83813. (function (BABYLON) {
  83814. /*
  83815. * Based on jsTGALoader - Javascript loader for TGA file
  83816. * By Vincent Thibault
  83817. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83818. */
  83819. var TGATools = /** @class */ (function () {
  83820. function TGATools() {
  83821. }
  83822. TGATools.GetTGAHeader = function (data) {
  83823. var offset = 0;
  83824. var header = {
  83825. id_length: data[offset++],
  83826. colormap_type: data[offset++],
  83827. image_type: data[offset++],
  83828. colormap_index: data[offset++] | data[offset++] << 8,
  83829. colormap_length: data[offset++] | data[offset++] << 8,
  83830. colormap_size: data[offset++],
  83831. origin: [
  83832. data[offset++] | data[offset++] << 8,
  83833. data[offset++] | data[offset++] << 8
  83834. ],
  83835. width: data[offset++] | data[offset++] << 8,
  83836. height: data[offset++] | data[offset++] << 8,
  83837. pixel_size: data[offset++],
  83838. flags: data[offset++]
  83839. };
  83840. return header;
  83841. };
  83842. TGATools.UploadContent = function (gl, data) {
  83843. // Not enough data to contain header ?
  83844. if (data.length < 19) {
  83845. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83846. return;
  83847. }
  83848. // Read Header
  83849. var offset = 18;
  83850. var header = TGATools.GetTGAHeader(data);
  83851. // Assume it's a valid Targa file.
  83852. if (header.id_length + offset > data.length) {
  83853. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83854. return;
  83855. }
  83856. // Skip not needed data
  83857. offset += header.id_length;
  83858. var use_rle = false;
  83859. var use_pal = false;
  83860. var use_grey = false;
  83861. // Get some informations.
  83862. switch (header.image_type) {
  83863. case TGATools._TYPE_RLE_INDEXED:
  83864. use_rle = true;
  83865. case TGATools._TYPE_INDEXED:
  83866. use_pal = true;
  83867. break;
  83868. case TGATools._TYPE_RLE_RGB:
  83869. use_rle = true;
  83870. case TGATools._TYPE_RGB:
  83871. // use_rgb = true;
  83872. break;
  83873. case TGATools._TYPE_RLE_GREY:
  83874. use_rle = true;
  83875. case TGATools._TYPE_GREY:
  83876. use_grey = true;
  83877. break;
  83878. }
  83879. var pixel_data;
  83880. // var numAlphaBits = header.flags & 0xf;
  83881. var pixel_size = header.pixel_size >> 3;
  83882. var pixel_total = header.width * header.height * pixel_size;
  83883. // Read palettes
  83884. var palettes;
  83885. if (use_pal) {
  83886. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83887. }
  83888. // Read LRE
  83889. if (use_rle) {
  83890. pixel_data = new Uint8Array(pixel_total);
  83891. var c, count, i;
  83892. var localOffset = 0;
  83893. var pixels = new Uint8Array(pixel_size);
  83894. while (offset < pixel_total && localOffset < pixel_total) {
  83895. c = data[offset++];
  83896. count = (c & 0x7f) + 1;
  83897. // RLE pixels
  83898. if (c & 0x80) {
  83899. // Bind pixel tmp array
  83900. for (i = 0; i < pixel_size; ++i) {
  83901. pixels[i] = data[offset++];
  83902. }
  83903. // Copy pixel array
  83904. for (i = 0; i < count; ++i) {
  83905. pixel_data.set(pixels, localOffset + i * pixel_size);
  83906. }
  83907. localOffset += pixel_size * count;
  83908. }
  83909. // Raw pixels
  83910. else {
  83911. count *= pixel_size;
  83912. for (i = 0; i < count; ++i) {
  83913. pixel_data[localOffset + i] = data[offset++];
  83914. }
  83915. localOffset += count;
  83916. }
  83917. }
  83918. }
  83919. // RAW Pixels
  83920. else {
  83921. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83922. }
  83923. // Load to texture
  83924. var x_start, y_start, x_step, y_step, y_end, x_end;
  83925. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83926. default:
  83927. case TGATools._ORIGIN_UL:
  83928. x_start = 0;
  83929. x_step = 1;
  83930. x_end = header.width;
  83931. y_start = 0;
  83932. y_step = 1;
  83933. y_end = header.height;
  83934. break;
  83935. case TGATools._ORIGIN_BL:
  83936. x_start = 0;
  83937. x_step = 1;
  83938. x_end = header.width;
  83939. y_start = header.height - 1;
  83940. y_step = -1;
  83941. y_end = -1;
  83942. break;
  83943. case TGATools._ORIGIN_UR:
  83944. x_start = header.width - 1;
  83945. x_step = -1;
  83946. x_end = -1;
  83947. y_start = 0;
  83948. y_step = 1;
  83949. y_end = header.height;
  83950. break;
  83951. case TGATools._ORIGIN_BR:
  83952. x_start = header.width - 1;
  83953. x_step = -1;
  83954. x_end = -1;
  83955. y_start = header.height - 1;
  83956. y_step = -1;
  83957. y_end = -1;
  83958. break;
  83959. }
  83960. // Load the specify method
  83961. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  83962. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  83963. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  83964. };
  83965. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83966. var image = pixel_data, colormap = palettes;
  83967. var width = header.width, height = header.height;
  83968. var color, i = 0, x, y;
  83969. var imageData = new Uint8Array(width * height * 4);
  83970. for (y = y_start; y !== y_end; y += y_step) {
  83971. for (x = x_start; x !== x_end; x += x_step, i++) {
  83972. color = image[i];
  83973. imageData[(x + width * y) * 4 + 3] = 255;
  83974. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  83975. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  83976. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  83977. }
  83978. }
  83979. return imageData;
  83980. };
  83981. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83982. var image = pixel_data;
  83983. var width = header.width, height = header.height;
  83984. var color, i = 0, x, y;
  83985. var imageData = new Uint8Array(width * height * 4);
  83986. for (y = y_start; y !== y_end; y += y_step) {
  83987. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83988. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  83989. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  83990. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  83991. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  83992. imageData[(x + width * y) * 4 + 0] = r;
  83993. imageData[(x + width * y) * 4 + 1] = g;
  83994. imageData[(x + width * y) * 4 + 2] = b;
  83995. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  83996. }
  83997. }
  83998. return imageData;
  83999. };
  84000. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84001. var image = pixel_data;
  84002. var width = header.width, height = header.height;
  84003. var i = 0, x, y;
  84004. var imageData = new Uint8Array(width * height * 4);
  84005. for (y = y_start; y !== y_end; y += y_step) {
  84006. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84007. imageData[(x + width * y) * 4 + 3] = 255;
  84008. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84009. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84010. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84011. }
  84012. }
  84013. return imageData;
  84014. };
  84015. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84016. var image = pixel_data;
  84017. var width = header.width, height = header.height;
  84018. var i = 0, x, y;
  84019. var imageData = new Uint8Array(width * height * 4);
  84020. for (y = y_start; y !== y_end; y += y_step) {
  84021. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84022. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84023. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84024. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84025. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84026. }
  84027. }
  84028. return imageData;
  84029. };
  84030. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84031. var image = pixel_data;
  84032. var width = header.width, height = header.height;
  84033. var color, i = 0, x, y;
  84034. var imageData = new Uint8Array(width * height * 4);
  84035. for (y = y_start; y !== y_end; y += y_step) {
  84036. for (x = x_start; x !== x_end; x += x_step, i++) {
  84037. color = image[i];
  84038. imageData[(x + width * y) * 4 + 0] = color;
  84039. imageData[(x + width * y) * 4 + 1] = color;
  84040. imageData[(x + width * y) * 4 + 2] = color;
  84041. imageData[(x + width * y) * 4 + 3] = 255;
  84042. }
  84043. }
  84044. return imageData;
  84045. };
  84046. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84047. var image = pixel_data;
  84048. var width = header.width, height = header.height;
  84049. var i = 0, x, y;
  84050. var imageData = new Uint8Array(width * height * 4);
  84051. for (y = y_start; y !== y_end; y += y_step) {
  84052. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84053. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84054. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84055. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84056. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84057. }
  84058. }
  84059. return imageData;
  84060. };
  84061. //private static _TYPE_NO_DATA = 0;
  84062. TGATools._TYPE_INDEXED = 1;
  84063. TGATools._TYPE_RGB = 2;
  84064. TGATools._TYPE_GREY = 3;
  84065. TGATools._TYPE_RLE_INDEXED = 9;
  84066. TGATools._TYPE_RLE_RGB = 10;
  84067. TGATools._TYPE_RLE_GREY = 11;
  84068. TGATools._ORIGIN_MASK = 0x30;
  84069. TGATools._ORIGIN_SHIFT = 0x04;
  84070. TGATools._ORIGIN_BL = 0x00;
  84071. TGATools._ORIGIN_BR = 0x01;
  84072. TGATools._ORIGIN_UL = 0x02;
  84073. TGATools._ORIGIN_UR = 0x03;
  84074. return TGATools;
  84075. }());
  84076. BABYLON.TGATools = TGATools;
  84077. })(BABYLON || (BABYLON = {}));
  84078. //# sourceMappingURL=babylon.tga.js.map
  84079. var BABYLON;
  84080. (function (BABYLON) {
  84081. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84082. // All values and structures referenced from:
  84083. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84084. var DDS_MAGIC = 0x20534444;
  84085. var
  84086. //DDSD_CAPS = 0x1,
  84087. //DDSD_HEIGHT = 0x2,
  84088. //DDSD_WIDTH = 0x4,
  84089. //DDSD_PITCH = 0x8,
  84090. //DDSD_PIXELFORMAT = 0x1000,
  84091. DDSD_MIPMAPCOUNT = 0x20000;
  84092. //DDSD_LINEARSIZE = 0x80000,
  84093. //DDSD_DEPTH = 0x800000;
  84094. // var DDSCAPS_COMPLEX = 0x8,
  84095. // DDSCAPS_MIPMAP = 0x400000,
  84096. // DDSCAPS_TEXTURE = 0x1000;
  84097. var DDSCAPS2_CUBEMAP = 0x200;
  84098. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84099. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84100. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84101. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84102. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84103. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84104. // DDSCAPS2_VOLUME = 0x200000;
  84105. var
  84106. //DDPF_ALPHAPIXELS = 0x1,
  84107. //DDPF_ALPHA = 0x2,
  84108. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84109. //DDPF_YUV = 0x200,
  84110. DDPF_LUMINANCE = 0x20000;
  84111. function FourCCToInt32(value) {
  84112. return value.charCodeAt(0) +
  84113. (value.charCodeAt(1) << 8) +
  84114. (value.charCodeAt(2) << 16) +
  84115. (value.charCodeAt(3) << 24);
  84116. }
  84117. function Int32ToFourCC(value) {
  84118. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84119. }
  84120. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84121. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84122. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84123. var FOURCC_DX10 = FourCCToInt32("DX10");
  84124. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84125. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84126. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84127. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84128. var headerLengthInt = 31; // The header length in 32 bit ints
  84129. // Offsets into the header array
  84130. var off_magic = 0;
  84131. var off_size = 1;
  84132. var off_flags = 2;
  84133. var off_height = 3;
  84134. var off_width = 4;
  84135. var off_mipmapCount = 7;
  84136. var off_pfFlags = 20;
  84137. var off_pfFourCC = 21;
  84138. var off_RGBbpp = 22;
  84139. var off_RMask = 23;
  84140. var off_GMask = 24;
  84141. var off_BMask = 25;
  84142. var off_AMask = 26;
  84143. // var off_caps1 = 27;
  84144. var off_caps2 = 28;
  84145. // var off_caps3 = 29;
  84146. // var off_caps4 = 30;
  84147. var off_dxgiFormat = 32;
  84148. ;
  84149. var DDSTools = /** @class */ (function () {
  84150. function DDSTools() {
  84151. }
  84152. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84153. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84154. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84155. var mipmapCount = 1;
  84156. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84157. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84158. }
  84159. var fourCC = header[off_pfFourCC];
  84160. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84161. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84162. switch (fourCC) {
  84163. case FOURCC_D3DFMT_R16G16B16A16F:
  84164. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84165. break;
  84166. case FOURCC_D3DFMT_R32G32B32A32F:
  84167. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84168. break;
  84169. case FOURCC_DX10:
  84170. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84171. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84172. break;
  84173. }
  84174. }
  84175. return {
  84176. width: header[off_width],
  84177. height: header[off_height],
  84178. mipmapCount: mipmapCount,
  84179. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84180. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84181. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84182. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84183. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84184. dxgiFormat: dxgiFormat,
  84185. textureType: textureType
  84186. };
  84187. };
  84188. DDSTools._ToHalfFloat = function (value) {
  84189. if (!DDSTools._FloatView) {
  84190. DDSTools._FloatView = new Float32Array(1);
  84191. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84192. }
  84193. DDSTools._FloatView[0] = value;
  84194. var x = DDSTools._Int32View[0];
  84195. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84196. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84197. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84198. /* If zero, or denormal, or exponent underflows too much for a denormal
  84199. * half, return signed zero. */
  84200. if (e < 103) {
  84201. return bits;
  84202. }
  84203. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84204. if (e > 142) {
  84205. bits |= 0x7c00;
  84206. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84207. * not Inf, so make sure we set one mantissa bit too. */
  84208. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84209. return bits;
  84210. }
  84211. /* If exponent underflows but not too much, return a denormal */
  84212. if (e < 113) {
  84213. m |= 0x0800;
  84214. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84215. * to 1, which is OK. */
  84216. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84217. return bits;
  84218. }
  84219. bits |= ((e - 112) << 10) | (m >> 1);
  84220. bits += m & 1;
  84221. return bits;
  84222. };
  84223. DDSTools._FromHalfFloat = function (value) {
  84224. var s = (value & 0x8000) >> 15;
  84225. var e = (value & 0x7C00) >> 10;
  84226. var f = value & 0x03FF;
  84227. if (e === 0) {
  84228. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84229. }
  84230. else if (e == 0x1F) {
  84231. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84232. }
  84233. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84234. };
  84235. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84236. var destArray = new Float32Array(dataLength);
  84237. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84238. var index = 0;
  84239. for (var y = 0; y < height; y++) {
  84240. for (var x = 0; x < width; x++) {
  84241. var srcPos = (x + y * width) * 4;
  84242. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84243. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84244. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84245. if (DDSTools.StoreLODInAlphaChannel) {
  84246. destArray[index + 3] = lod;
  84247. }
  84248. else {
  84249. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84250. }
  84251. index += 4;
  84252. }
  84253. }
  84254. return destArray;
  84255. };
  84256. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84257. if (DDSTools.StoreLODInAlphaChannel) {
  84258. var destArray = new Uint16Array(dataLength);
  84259. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84260. var index = 0;
  84261. for (var y = 0; y < height; y++) {
  84262. for (var x = 0; x < width; x++) {
  84263. var srcPos = (x + y * width) * 4;
  84264. destArray[index] = srcData[srcPos];
  84265. destArray[index + 1] = srcData[srcPos + 1];
  84266. destArray[index + 2] = srcData[srcPos + 2];
  84267. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84268. index += 4;
  84269. }
  84270. }
  84271. return destArray;
  84272. }
  84273. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84274. };
  84275. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84276. if (DDSTools.StoreLODInAlphaChannel) {
  84277. var destArray = new Float32Array(dataLength);
  84278. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84279. var index = 0;
  84280. for (var y = 0; y < height; y++) {
  84281. for (var x = 0; x < width; x++) {
  84282. var srcPos = (x + y * width) * 4;
  84283. destArray[index] = srcData[srcPos];
  84284. destArray[index + 1] = srcData[srcPos + 1];
  84285. destArray[index + 2] = srcData[srcPos + 2];
  84286. destArray[index + 3] = lod;
  84287. index += 4;
  84288. }
  84289. }
  84290. return destArray;
  84291. }
  84292. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84293. };
  84294. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84295. var destArray = new Uint8Array(dataLength);
  84296. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84297. var index = 0;
  84298. for (var y = 0; y < height; y++) {
  84299. for (var x = 0; x < width; x++) {
  84300. var srcPos = (x + y * width) * 4;
  84301. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84302. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84303. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84304. if (DDSTools.StoreLODInAlphaChannel) {
  84305. destArray[index + 3] = lod;
  84306. }
  84307. else {
  84308. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84309. }
  84310. index += 4;
  84311. }
  84312. }
  84313. return destArray;
  84314. };
  84315. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84316. var destArray = new Uint8Array(dataLength);
  84317. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84318. var index = 0;
  84319. for (var y = 0; y < height; y++) {
  84320. for (var x = 0; x < width; x++) {
  84321. var srcPos = (x + y * width) * 4;
  84322. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84323. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84324. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84325. if (DDSTools.StoreLODInAlphaChannel) {
  84326. destArray[index + 3] = lod;
  84327. }
  84328. else {
  84329. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84330. }
  84331. index += 4;
  84332. }
  84333. }
  84334. return destArray;
  84335. };
  84336. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84337. var byteArray = new Uint8Array(dataLength);
  84338. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84339. var index = 0;
  84340. for (var y = 0; y < height; y++) {
  84341. for (var x = 0; x < width; x++) {
  84342. var srcPos = (x + y * width) * 4;
  84343. byteArray[index] = srcData[srcPos + rOffset];
  84344. byteArray[index + 1] = srcData[srcPos + gOffset];
  84345. byteArray[index + 2] = srcData[srcPos + bOffset];
  84346. byteArray[index + 3] = srcData[srcPos + aOffset];
  84347. index += 4;
  84348. }
  84349. }
  84350. return byteArray;
  84351. };
  84352. DDSTools._ExtractLongWordOrder = function (value) {
  84353. if (value === 0 || value === 255 || value === -16777216) {
  84354. return 0;
  84355. }
  84356. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84357. };
  84358. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84359. var byteArray = new Uint8Array(dataLength);
  84360. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84361. var index = 0;
  84362. for (var y = 0; y < height; y++) {
  84363. for (var x = 0; x < width; x++) {
  84364. var srcPos = (x + y * width) * 3;
  84365. byteArray[index] = srcData[srcPos + rOffset];
  84366. byteArray[index + 1] = srcData[srcPos + gOffset];
  84367. byteArray[index + 2] = srcData[srcPos + bOffset];
  84368. index += 3;
  84369. }
  84370. }
  84371. return byteArray;
  84372. };
  84373. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84374. var byteArray = new Uint8Array(dataLength);
  84375. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84376. var index = 0;
  84377. for (var y = 0; y < height; y++) {
  84378. for (var x = 0; x < width; x++) {
  84379. var srcPos = (x + y * width);
  84380. byteArray[index] = srcData[srcPos];
  84381. index++;
  84382. }
  84383. }
  84384. return byteArray;
  84385. };
  84386. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84387. if (lodIndex === void 0) { lodIndex = -1; }
  84388. var sphericalPolynomialFaces = null;
  84389. if (info.sphericalPolynomial) {
  84390. sphericalPolynomialFaces = new Array();
  84391. }
  84392. var ext = engine.getCaps().s3tc;
  84393. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84394. var fourCC, width, height, dataLength = 0, dataOffset;
  84395. var byteArray, mipmapCount, mip;
  84396. var internalFormat = 0;
  84397. var format = 0;
  84398. var blockBytes = 1;
  84399. if (header[off_magic] !== DDS_MAGIC) {
  84400. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84401. return;
  84402. }
  84403. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84404. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84405. return;
  84406. }
  84407. if (info.isCompressed && !ext) {
  84408. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84409. return;
  84410. }
  84411. var bpp = header[off_RGBbpp];
  84412. dataOffset = header[off_size] + 4;
  84413. var computeFormats = false;
  84414. if (info.isFourCC) {
  84415. fourCC = header[off_pfFourCC];
  84416. switch (fourCC) {
  84417. case FOURCC_DXT1:
  84418. blockBytes = 8;
  84419. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84420. break;
  84421. case FOURCC_DXT3:
  84422. blockBytes = 16;
  84423. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84424. break;
  84425. case FOURCC_DXT5:
  84426. blockBytes = 16;
  84427. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84428. break;
  84429. case FOURCC_D3DFMT_R16G16B16A16F:
  84430. computeFormats = true;
  84431. break;
  84432. case FOURCC_D3DFMT_R32G32B32A32F:
  84433. computeFormats = true;
  84434. break;
  84435. case FOURCC_DX10:
  84436. // There is an additionnal header so dataOffset need to be changed
  84437. dataOffset += 5 * 4; // 5 uints
  84438. var supported = false;
  84439. switch (info.dxgiFormat) {
  84440. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84441. computeFormats = true;
  84442. supported = true;
  84443. break;
  84444. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84445. info.isRGB = true;
  84446. info.isFourCC = false;
  84447. bpp = 32;
  84448. supported = true;
  84449. break;
  84450. }
  84451. if (supported) {
  84452. break;
  84453. }
  84454. default:
  84455. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84456. return;
  84457. }
  84458. }
  84459. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84460. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84461. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84462. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84463. if (computeFormats) {
  84464. format = engine._getWebGLTextureType(info.textureType);
  84465. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84466. }
  84467. mipmapCount = 1;
  84468. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84469. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84470. }
  84471. for (var face = 0; face < faces; face++) {
  84472. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84473. width = header[off_width];
  84474. height = header[off_height];
  84475. for (mip = 0; mip < mipmapCount; ++mip) {
  84476. if (lodIndex === -1 || lodIndex === mip) {
  84477. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84478. var i = (lodIndex === -1) ? mip : 0;
  84479. if (!info.isCompressed && info.isFourCC) {
  84480. dataLength = width * height * 4;
  84481. var floatArray = null;
  84482. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84483. if (bpp === 128) {
  84484. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84485. if (sphericalPolynomialFaces && i == 0) {
  84486. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84487. }
  84488. }
  84489. else if (bpp === 64) {
  84490. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84491. if (sphericalPolynomialFaces && i == 0) {
  84492. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84493. }
  84494. }
  84495. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84496. format = engine._getWebGLTextureType(info.textureType);
  84497. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84498. }
  84499. else {
  84500. if (bpp === 128) {
  84501. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84502. if (sphericalPolynomialFaces && i == 0) {
  84503. sphericalPolynomialFaces.push(floatArray);
  84504. }
  84505. }
  84506. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84507. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84508. if (sphericalPolynomialFaces && i == 0) {
  84509. sphericalPolynomialFaces.push(floatArray);
  84510. }
  84511. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84512. format = engine._getWebGLTextureType(info.textureType);
  84513. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84514. }
  84515. else { // 64
  84516. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84517. if (sphericalPolynomialFaces && i == 0) {
  84518. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84519. }
  84520. }
  84521. }
  84522. if (floatArray) {
  84523. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84524. }
  84525. }
  84526. else if (info.isRGB) {
  84527. if (bpp === 24) {
  84528. dataLength = width * height * 3;
  84529. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84530. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84531. }
  84532. else { // 32
  84533. dataLength = width * height * 4;
  84534. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84535. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84536. }
  84537. }
  84538. else if (info.isLuminance) {
  84539. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84540. var unpaddedRowSize = width;
  84541. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84542. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84543. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84544. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84545. }
  84546. else {
  84547. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84548. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84549. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84550. }
  84551. }
  84552. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84553. width *= 0.5;
  84554. height *= 0.5;
  84555. width = Math.max(1.0, width);
  84556. height = Math.max(1.0, height);
  84557. }
  84558. if (currentFace !== undefined) {
  84559. // Loading a single face
  84560. break;
  84561. }
  84562. }
  84563. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84564. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84565. size: header[off_width],
  84566. right: sphericalPolynomialFaces[0],
  84567. left: sphericalPolynomialFaces[1],
  84568. up: sphericalPolynomialFaces[2],
  84569. down: sphericalPolynomialFaces[3],
  84570. front: sphericalPolynomialFaces[4],
  84571. back: sphericalPolynomialFaces[5],
  84572. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84573. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84574. gammaSpace: false,
  84575. });
  84576. }
  84577. else {
  84578. info.sphericalPolynomial = undefined;
  84579. }
  84580. };
  84581. DDSTools.StoreLODInAlphaChannel = false;
  84582. return DDSTools;
  84583. }());
  84584. BABYLON.DDSTools = DDSTools;
  84585. })(BABYLON || (BABYLON = {}));
  84586. //# sourceMappingURL=babylon.dds.js.map
  84587. var BABYLON;
  84588. (function (BABYLON) {
  84589. /**
  84590. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84591. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84592. */
  84593. var KhronosTextureContainer = /** @class */ (function () {
  84594. /**
  84595. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84596. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84597. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84598. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84599. */
  84600. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84601. this.arrayBuffer = arrayBuffer;
  84602. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84603. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84604. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84605. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84606. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84607. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84608. BABYLON.Tools.Error("texture missing KTX identifier");
  84609. return;
  84610. }
  84611. // load the reset of the header in native 32 bit int
  84612. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84613. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84614. var oppositeEndianess = header[0] === 0x01020304;
  84615. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84616. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84617. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84618. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84619. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84620. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84621. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84622. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84623. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84624. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84625. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84626. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84627. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84628. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84629. if (this.glType !== 0) {
  84630. BABYLON.Tools.Error("only compressed formats currently supported");
  84631. return;
  84632. }
  84633. else {
  84634. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84635. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84636. }
  84637. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84638. BABYLON.Tools.Error("only 2D textures currently supported");
  84639. return;
  84640. }
  84641. if (this.numberOfArrayElements !== 0) {
  84642. BABYLON.Tools.Error("texture arrays not currently supported");
  84643. return;
  84644. }
  84645. if (this.numberOfFaces !== facesExpected) {
  84646. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84647. return;
  84648. }
  84649. // we now have a completely validated file, so could use existence of loadType as success
  84650. // would need to make this more elaborate & adjust checks above to support more than one load type
  84651. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84652. }
  84653. // not as fast hardware based, but will probably never need to use
  84654. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84655. return ((val & 0xFF) << 24)
  84656. | ((val & 0xFF00) << 8)
  84657. | ((val >> 8) & 0xFF00)
  84658. | ((val >> 24) & 0xFF);
  84659. };
  84660. /**
  84661. * It is assumed that the texture has already been created & is currently bound
  84662. */
  84663. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84664. switch (this.loadType) {
  84665. case KhronosTextureContainer.COMPRESSED_2D:
  84666. this._upload2DCompressedLevels(gl, loadMipmaps);
  84667. break;
  84668. case KhronosTextureContainer.TEX_2D:
  84669. case KhronosTextureContainer.COMPRESSED_3D:
  84670. case KhronosTextureContainer.TEX_3D:
  84671. }
  84672. };
  84673. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84674. // initialize width & height for level 1
  84675. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84676. var width = this.pixelWidth;
  84677. var height = this.pixelHeight;
  84678. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84679. for (var level = 0; level < mipmapCount; level++) {
  84680. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84681. for (var face = 0; face < this.numberOfFaces; face++) {
  84682. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84683. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84684. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84685. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84686. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84687. }
  84688. width = Math.max(1.0, width * 0.5);
  84689. height = Math.max(1.0, height * 0.5);
  84690. }
  84691. };
  84692. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84693. // load types
  84694. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84695. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84696. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84697. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84698. return KhronosTextureContainer;
  84699. }());
  84700. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84701. })(BABYLON || (BABYLON = {}));
  84702. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84703. var BABYLON;
  84704. (function (BABYLON) {
  84705. var Debug;
  84706. (function (Debug) {
  84707. /**
  84708. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84709. */
  84710. var SkeletonViewer = /** @class */ (function () {
  84711. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84712. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84713. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84714. this.skeleton = skeleton;
  84715. this.mesh = mesh;
  84716. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84717. this.renderingGroupId = renderingGroupId;
  84718. this.color = BABYLON.Color3.White();
  84719. this._debugLines = new Array();
  84720. this._isEnabled = false;
  84721. this._scene = scene;
  84722. this.update();
  84723. this._renderFunction = this.update.bind(this);
  84724. }
  84725. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84726. get: function () {
  84727. return this._isEnabled;
  84728. },
  84729. set: function (value) {
  84730. if (this._isEnabled === value) {
  84731. return;
  84732. }
  84733. this._isEnabled = value;
  84734. if (value) {
  84735. this._scene.registerBeforeRender(this._renderFunction);
  84736. }
  84737. else {
  84738. this._scene.unregisterBeforeRender(this._renderFunction);
  84739. }
  84740. },
  84741. enumerable: true,
  84742. configurable: true
  84743. });
  84744. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84745. if (x === void 0) { x = 0; }
  84746. if (y === void 0) { y = 0; }
  84747. if (z === void 0) { z = 0; }
  84748. var tmat = BABYLON.Tmp.Matrix[0];
  84749. var parentBone = bone.getParent();
  84750. tmat.copyFrom(bone.getLocalMatrix());
  84751. if (x !== 0 || y !== 0 || z !== 0) {
  84752. var tmat2 = BABYLON.Tmp.Matrix[1];
  84753. BABYLON.Matrix.IdentityToRef(tmat2);
  84754. tmat2.m[12] = x;
  84755. tmat2.m[13] = y;
  84756. tmat2.m[14] = z;
  84757. tmat2.multiplyToRef(tmat, tmat);
  84758. }
  84759. if (parentBone) {
  84760. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84761. }
  84762. tmat.multiplyToRef(meshMat, tmat);
  84763. position.x = tmat.m[12];
  84764. position.y = tmat.m[13];
  84765. position.z = tmat.m[14];
  84766. };
  84767. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84768. var len = bones.length;
  84769. var meshPos = this.mesh.position;
  84770. for (var i = 0; i < len; i++) {
  84771. var bone = bones[i];
  84772. var points = this._debugLines[i];
  84773. if (!points) {
  84774. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84775. this._debugLines[i] = points;
  84776. }
  84777. this._getBonePosition(points[0], bone, meshMat);
  84778. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84779. points[0].subtractInPlace(meshPos);
  84780. points[1].subtractInPlace(meshPos);
  84781. }
  84782. };
  84783. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84784. var len = bones.length;
  84785. var boneNum = 0;
  84786. var meshPos = this.mesh.position;
  84787. for (var i = len - 1; i >= 0; i--) {
  84788. var childBone = bones[i];
  84789. var parentBone = childBone.getParent();
  84790. if (!parentBone) {
  84791. continue;
  84792. }
  84793. var points = this._debugLines[boneNum];
  84794. if (!points) {
  84795. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84796. this._debugLines[boneNum] = points;
  84797. }
  84798. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84799. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84800. points[0].subtractInPlace(meshPos);
  84801. points[1].subtractInPlace(meshPos);
  84802. boneNum++;
  84803. }
  84804. };
  84805. SkeletonViewer.prototype.update = function () {
  84806. if (this.autoUpdateBonesMatrices) {
  84807. this.skeleton.computeAbsoluteTransforms();
  84808. }
  84809. if (this.skeleton.bones[0].length === undefined) {
  84810. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84811. }
  84812. else {
  84813. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84814. }
  84815. if (!this._debugMesh) {
  84816. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84817. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84818. }
  84819. else {
  84820. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84821. }
  84822. this._debugMesh.position.copyFrom(this.mesh.position);
  84823. this._debugMesh.color = this.color;
  84824. };
  84825. SkeletonViewer.prototype.dispose = function () {
  84826. if (this._debugMesh) {
  84827. this.isEnabled = false;
  84828. this._debugMesh.dispose();
  84829. this._debugMesh = null;
  84830. }
  84831. };
  84832. return SkeletonViewer;
  84833. }());
  84834. Debug.SkeletonViewer = SkeletonViewer;
  84835. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84836. })(BABYLON || (BABYLON = {}));
  84837. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84838. /**
  84839. * Module Debug contains the (visual) components to debug a scene correctly
  84840. */
  84841. var BABYLON;
  84842. (function (BABYLON) {
  84843. var Debug;
  84844. (function (Debug) {
  84845. /**
  84846. * The Axes viewer will show 3 axes in a specific point in space
  84847. */
  84848. var AxesViewer = /** @class */ (function () {
  84849. function AxesViewer(scene, scaleLines) {
  84850. if (scaleLines === void 0) { scaleLines = 1; }
  84851. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84852. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84853. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84854. this.scaleLines = 1;
  84855. this.scaleLines = scaleLines;
  84856. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84857. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84858. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84859. this._xmesh.renderingGroupId = 2;
  84860. this._ymesh.renderingGroupId = 2;
  84861. this._zmesh.renderingGroupId = 2;
  84862. this._xmesh.material.checkReadyOnlyOnce = true;
  84863. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84864. this._ymesh.material.checkReadyOnlyOnce = true;
  84865. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84866. this._zmesh.material.checkReadyOnlyOnce = true;
  84867. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84868. this.scene = scene;
  84869. }
  84870. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84871. var scaleLines = this.scaleLines;
  84872. if (this._xmesh) {
  84873. this._xmesh.position.copyFrom(position);
  84874. }
  84875. if (this._ymesh) {
  84876. this._ymesh.position.copyFrom(position);
  84877. }
  84878. if (this._zmesh) {
  84879. this._zmesh.position.copyFrom(position);
  84880. }
  84881. var point2 = this._xline[1];
  84882. point2.x = xaxis.x * scaleLines;
  84883. point2.y = xaxis.y * scaleLines;
  84884. point2.z = xaxis.z * scaleLines;
  84885. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84886. point2 = this._yline[1];
  84887. point2.x = yaxis.x * scaleLines;
  84888. point2.y = yaxis.y * scaleLines;
  84889. point2.z = yaxis.z * scaleLines;
  84890. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84891. point2 = this._zline[1];
  84892. point2.x = zaxis.x * scaleLines;
  84893. point2.y = zaxis.y * scaleLines;
  84894. point2.z = zaxis.z * scaleLines;
  84895. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84896. };
  84897. AxesViewer.prototype.dispose = function () {
  84898. if (this._xmesh) {
  84899. this._xmesh.dispose();
  84900. }
  84901. if (this._ymesh) {
  84902. this._ymesh.dispose();
  84903. }
  84904. if (this._zmesh) {
  84905. this._zmesh.dispose();
  84906. }
  84907. this._xmesh = null;
  84908. this._ymesh = null;
  84909. this._zmesh = null;
  84910. this.scene = null;
  84911. };
  84912. return AxesViewer;
  84913. }());
  84914. Debug.AxesViewer = AxesViewer;
  84915. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84916. })(BABYLON || (BABYLON = {}));
  84917. //# sourceMappingURL=babylon.axesViewer.js.map
  84918. var BABYLON;
  84919. (function (BABYLON) {
  84920. var Debug;
  84921. (function (Debug) {
  84922. /**
  84923. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84924. */
  84925. var BoneAxesViewer = /** @class */ (function (_super) {
  84926. __extends(BoneAxesViewer, _super);
  84927. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84928. if (scaleLines === void 0) { scaleLines = 1; }
  84929. var _this = _super.call(this, scene, scaleLines) || this;
  84930. _this.pos = BABYLON.Vector3.Zero();
  84931. _this.xaxis = BABYLON.Vector3.Zero();
  84932. _this.yaxis = BABYLON.Vector3.Zero();
  84933. _this.zaxis = BABYLON.Vector3.Zero();
  84934. _this.mesh = mesh;
  84935. _this.bone = bone;
  84936. return _this;
  84937. }
  84938. BoneAxesViewer.prototype.update = function () {
  84939. if (!this.mesh || !this.bone) {
  84940. return;
  84941. }
  84942. var bone = this.bone;
  84943. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  84944. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  84945. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  84946. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  84947. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  84948. };
  84949. BoneAxesViewer.prototype.dispose = function () {
  84950. if (this.mesh) {
  84951. this.mesh = null;
  84952. this.bone = null;
  84953. _super.prototype.dispose.call(this);
  84954. }
  84955. };
  84956. return BoneAxesViewer;
  84957. }(Debug.AxesViewer));
  84958. Debug.BoneAxesViewer = BoneAxesViewer;
  84959. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84960. })(BABYLON || (BABYLON = {}));
  84961. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  84962. var BABYLON;
  84963. (function (BABYLON) {
  84964. var RayHelper = /** @class */ (function () {
  84965. function RayHelper(ray) {
  84966. this.ray = ray;
  84967. }
  84968. RayHelper.CreateAndShow = function (ray, scene, color) {
  84969. var helper = new RayHelper(ray);
  84970. helper.show(scene, color);
  84971. return helper;
  84972. };
  84973. RayHelper.prototype.show = function (scene, color) {
  84974. if (!this._renderFunction && this.ray) {
  84975. var ray = this.ray;
  84976. this._renderFunction = this._render.bind(this);
  84977. this._scene = scene;
  84978. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  84979. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  84980. if (this._renderFunction) {
  84981. this._scene.registerBeforeRender(this._renderFunction);
  84982. }
  84983. }
  84984. if (color && this._renderLine) {
  84985. this._renderLine.color.copyFrom(color);
  84986. }
  84987. };
  84988. RayHelper.prototype.hide = function () {
  84989. if (this._renderFunction && this._scene) {
  84990. this._scene.unregisterBeforeRender(this._renderFunction);
  84991. this._scene = null;
  84992. this._renderFunction = null;
  84993. if (this._renderLine) {
  84994. this._renderLine.dispose();
  84995. this._renderLine = null;
  84996. }
  84997. this._renderPoints = [];
  84998. }
  84999. };
  85000. RayHelper.prototype._render = function () {
  85001. var ray = this.ray;
  85002. if (!ray) {
  85003. return;
  85004. }
  85005. var point = this._renderPoints[1];
  85006. var len = Math.min(ray.length, 1000000);
  85007. point.copyFrom(ray.direction);
  85008. point.scaleInPlace(len);
  85009. point.addInPlace(ray.origin);
  85010. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85011. };
  85012. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85013. this._attachedToMesh = mesh;
  85014. var ray = this.ray;
  85015. if (!ray) {
  85016. return;
  85017. }
  85018. if (!ray.direction) {
  85019. ray.direction = BABYLON.Vector3.Zero();
  85020. }
  85021. if (!ray.origin) {
  85022. ray.origin = BABYLON.Vector3.Zero();
  85023. }
  85024. if (length) {
  85025. ray.length = length;
  85026. }
  85027. if (!meshSpaceOrigin) {
  85028. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85029. }
  85030. if (!meshSpaceDirection) {
  85031. // -1 so that this will work with Mesh.lookAt
  85032. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85033. }
  85034. if (!this._meshSpaceDirection) {
  85035. this._meshSpaceDirection = meshSpaceDirection.clone();
  85036. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85037. }
  85038. else {
  85039. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85040. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85041. }
  85042. if (!this._updateToMeshFunction) {
  85043. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85044. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85045. }
  85046. this._updateToMesh();
  85047. };
  85048. RayHelper.prototype.detachFromMesh = function () {
  85049. if (this._attachedToMesh) {
  85050. if (this._updateToMeshFunction) {
  85051. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85052. }
  85053. this._attachedToMesh = null;
  85054. this._updateToMeshFunction = null;
  85055. }
  85056. };
  85057. RayHelper.prototype._updateToMesh = function () {
  85058. var ray = this.ray;
  85059. if (!this._attachedToMesh || !ray) {
  85060. return;
  85061. }
  85062. if (this._attachedToMesh._isDisposed) {
  85063. this.detachFromMesh();
  85064. return;
  85065. }
  85066. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85067. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85068. };
  85069. RayHelper.prototype.dispose = function () {
  85070. this.hide();
  85071. this.detachFromMesh();
  85072. this.ray = null;
  85073. };
  85074. return RayHelper;
  85075. }());
  85076. BABYLON.RayHelper = RayHelper;
  85077. })(BABYLON || (BABYLON = {}));
  85078. //# sourceMappingURL=babylon.rayHelper.js.map
  85079. var BABYLON;
  85080. (function (BABYLON) {
  85081. // load the inspector using require, if not present in the global namespace.
  85082. var DebugLayer = /** @class */ (function () {
  85083. function DebugLayer(scene) {
  85084. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85085. this._scene = scene;
  85086. // load inspector using require, if it doesn't exist on the global namespace.
  85087. }
  85088. /** Creates the inspector window. */
  85089. DebugLayer.prototype._createInspector = function (config) {
  85090. if (config === void 0) { config = {}; }
  85091. var popup = config.popup || false;
  85092. var initialTab = config.initialTab || 0;
  85093. var parentElement = config.parentElement || null;
  85094. if (!this._inspector) {
  85095. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85096. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85097. } // else nothing to do,; instance is already existing
  85098. };
  85099. DebugLayer.prototype.isVisible = function () {
  85100. if (!this._inspector) {
  85101. return false;
  85102. }
  85103. return true;
  85104. };
  85105. DebugLayer.prototype.hide = function () {
  85106. if (this._inspector) {
  85107. try {
  85108. this._inspector.dispose();
  85109. }
  85110. catch (e) {
  85111. // If the inspector has been removed directly from the inspector tool
  85112. }
  85113. this._inspector = null;
  85114. }
  85115. };
  85116. DebugLayer.prototype.show = function (config) {
  85117. if (config === void 0) { config = {}; }
  85118. if (typeof this.BJSINSPECTOR == 'undefined') {
  85119. // Load inspector and add it to the DOM
  85120. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85121. }
  85122. else {
  85123. // Otherwise creates the inspector
  85124. this._createInspector(config);
  85125. }
  85126. };
  85127. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85128. return DebugLayer;
  85129. }());
  85130. BABYLON.DebugLayer = DebugLayer;
  85131. })(BABYLON || (BABYLON = {}));
  85132. //# sourceMappingURL=babylon.debugLayer.js.map
  85133. var BABYLON;
  85134. (function (BABYLON) {
  85135. var Debug;
  85136. (function (Debug) {
  85137. /**
  85138. * Used to show the physics impostor around the specific mesh.
  85139. */
  85140. var PhysicsViewer = /** @class */ (function () {
  85141. function PhysicsViewer(scene) {
  85142. this._impostors = [];
  85143. this._meshes = [];
  85144. this._numMeshes = 0;
  85145. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85146. var physicEngine = this._scene.getPhysicsEngine();
  85147. if (physicEngine) {
  85148. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85149. }
  85150. }
  85151. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85152. var plugin = this._physicsEnginePlugin;
  85153. for (var i = 0; i < this._numMeshes; i++) {
  85154. var impostor = this._impostors[i];
  85155. if (!impostor) {
  85156. continue;
  85157. }
  85158. if (impostor.isDisposed) {
  85159. this.hideImpostor(this._impostors[i--]);
  85160. }
  85161. else {
  85162. var mesh = this._meshes[i];
  85163. if (mesh && plugin) {
  85164. plugin.syncMeshWithImpostor(mesh, impostor);
  85165. }
  85166. }
  85167. }
  85168. };
  85169. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85170. if (!this._scene) {
  85171. return;
  85172. }
  85173. for (var i = 0; i < this._numMeshes; i++) {
  85174. if (this._impostors[i] == impostor) {
  85175. return;
  85176. }
  85177. }
  85178. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85179. if (debugMesh) {
  85180. this._impostors[this._numMeshes] = impostor;
  85181. this._meshes[this._numMeshes] = debugMesh;
  85182. if (this._numMeshes === 0) {
  85183. this._renderFunction = this._updateDebugMeshes.bind(this);
  85184. this._scene.registerBeforeRender(this._renderFunction);
  85185. }
  85186. this._numMeshes++;
  85187. }
  85188. };
  85189. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85190. if (!impostor || !this._scene) {
  85191. return;
  85192. }
  85193. var removed = false;
  85194. for (var i = 0; i < this._numMeshes; i++) {
  85195. if (this._impostors[i] == impostor) {
  85196. var mesh = this._meshes[i];
  85197. if (!mesh) {
  85198. continue;
  85199. }
  85200. this._scene.removeMesh(mesh);
  85201. mesh.dispose();
  85202. this._numMeshes--;
  85203. if (this._numMeshes > 0) {
  85204. this._meshes[i] = this._meshes[this._numMeshes];
  85205. this._impostors[i] = this._impostors[this._numMeshes];
  85206. this._meshes[this._numMeshes] = null;
  85207. this._impostors[this._numMeshes] = null;
  85208. }
  85209. else {
  85210. this._meshes[0] = null;
  85211. this._impostors[0] = null;
  85212. }
  85213. removed = true;
  85214. break;
  85215. }
  85216. }
  85217. if (removed && this._numMeshes === 0) {
  85218. this._scene.unregisterBeforeRender(this._renderFunction);
  85219. }
  85220. };
  85221. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85222. if (!this._debugMaterial) {
  85223. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85224. this._debugMaterial.wireframe = true;
  85225. }
  85226. return this._debugMaterial;
  85227. };
  85228. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85229. if (!this._debugBoxMesh) {
  85230. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85231. this._debugBoxMesh.renderingGroupId = 1;
  85232. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85233. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85234. scene.removeMesh(this._debugBoxMesh);
  85235. }
  85236. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85237. };
  85238. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85239. if (!this._debugSphereMesh) {
  85240. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85241. this._debugSphereMesh.renderingGroupId = 1;
  85242. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85243. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85244. scene.removeMesh(this._debugSphereMesh);
  85245. }
  85246. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85247. };
  85248. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85249. var mesh = null;
  85250. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85251. mesh = this._getDebugBoxMesh(scene);
  85252. impostor.getBoxSizeToRef(mesh.scaling);
  85253. }
  85254. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85255. mesh = this._getDebugSphereMesh(scene);
  85256. var radius = impostor.getRadius();
  85257. mesh.scaling.x = radius * 2;
  85258. mesh.scaling.y = radius * 2;
  85259. mesh.scaling.z = radius * 2;
  85260. }
  85261. return mesh;
  85262. };
  85263. PhysicsViewer.prototype.dispose = function () {
  85264. for (var i = 0; i < this._numMeshes; i++) {
  85265. this.hideImpostor(this._impostors[i]);
  85266. }
  85267. if (this._debugBoxMesh) {
  85268. this._debugBoxMesh.dispose();
  85269. }
  85270. if (this._debugSphereMesh) {
  85271. this._debugSphereMesh.dispose();
  85272. }
  85273. if (this._debugMaterial) {
  85274. this._debugMaterial.dispose();
  85275. }
  85276. this._impostors.length = 0;
  85277. this._scene = null;
  85278. this._physicsEnginePlugin = null;
  85279. };
  85280. return PhysicsViewer;
  85281. }());
  85282. Debug.PhysicsViewer = PhysicsViewer;
  85283. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85284. })(BABYLON || (BABYLON = {}));
  85285. //# sourceMappingURL=babylon.physicsViewer.js.map
  85286. var BABYLON;
  85287. (function (BABYLON) {
  85288. var BoundingBoxRenderer = /** @class */ (function () {
  85289. function BoundingBoxRenderer(scene) {
  85290. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85291. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85292. this.showBackLines = true;
  85293. this.renderList = new BABYLON.SmartArray(32);
  85294. this._vertexBuffers = {};
  85295. this._scene = scene;
  85296. }
  85297. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85298. if (this._colorShader) {
  85299. return;
  85300. }
  85301. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85302. attributes: [BABYLON.VertexBuffer.PositionKind],
  85303. uniforms: ["world", "viewProjection", "color"]
  85304. });
  85305. var engine = this._scene.getEngine();
  85306. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85307. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85308. this._createIndexBuffer();
  85309. };
  85310. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85311. var engine = this._scene.getEngine();
  85312. 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]);
  85313. };
  85314. BoundingBoxRenderer.prototype._rebuild = function () {
  85315. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85316. if (vb) {
  85317. vb._rebuild();
  85318. }
  85319. this._createIndexBuffer();
  85320. };
  85321. BoundingBoxRenderer.prototype.reset = function () {
  85322. this.renderList.reset();
  85323. };
  85324. BoundingBoxRenderer.prototype.render = function () {
  85325. if (this.renderList.length === 0) {
  85326. return;
  85327. }
  85328. this._prepareRessources();
  85329. if (!this._colorShader.isReady()) {
  85330. return;
  85331. }
  85332. var engine = this._scene.getEngine();
  85333. engine.setDepthWrite(false);
  85334. this._colorShader._preBind();
  85335. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85336. var boundingBox = this.renderList.data[boundingBoxIndex];
  85337. var min = boundingBox.minimum;
  85338. var max = boundingBox.maximum;
  85339. var diff = max.subtract(min);
  85340. var median = min.add(diff.scale(0.5));
  85341. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85342. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85343. .multiply(boundingBox.getWorldMatrix());
  85344. // VBOs
  85345. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85346. if (this.showBackLines) {
  85347. // Back
  85348. engine.setDepthFunctionToGreaterOrEqual();
  85349. this._scene.resetCachedMaterial();
  85350. this._colorShader.setColor4("color", this.backColor.toColor4());
  85351. this._colorShader.bind(worldMatrix);
  85352. // Draw order
  85353. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85354. }
  85355. // Front
  85356. engine.setDepthFunctionToLess();
  85357. this._scene.resetCachedMaterial();
  85358. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85359. this._colorShader.bind(worldMatrix);
  85360. // Draw order
  85361. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85362. }
  85363. this._colorShader.unbind();
  85364. engine.setDepthFunctionToLessOrEqual();
  85365. engine.setDepthWrite(true);
  85366. };
  85367. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85368. this._prepareRessources();
  85369. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85370. return;
  85371. }
  85372. var engine = this._scene.getEngine();
  85373. engine.setDepthWrite(false);
  85374. engine.setColorWrite(false);
  85375. this._colorShader._preBind();
  85376. var boundingBox = mesh._boundingInfo.boundingBox;
  85377. var min = boundingBox.minimum;
  85378. var max = boundingBox.maximum;
  85379. var diff = max.subtract(min);
  85380. var median = min.add(diff.scale(0.5));
  85381. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85382. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85383. .multiply(boundingBox.getWorldMatrix());
  85384. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85385. engine.setDepthFunctionToLess();
  85386. this._scene.resetCachedMaterial();
  85387. this._colorShader.bind(worldMatrix);
  85388. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85389. this._colorShader.unbind();
  85390. engine.setDepthFunctionToLessOrEqual();
  85391. engine.setDepthWrite(true);
  85392. engine.setColorWrite(true);
  85393. };
  85394. BoundingBoxRenderer.prototype.dispose = function () {
  85395. if (!this._colorShader) {
  85396. return;
  85397. }
  85398. this.renderList.dispose();
  85399. this._colorShader.dispose();
  85400. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85401. if (buffer) {
  85402. buffer.dispose();
  85403. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85404. }
  85405. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85406. };
  85407. return BoundingBoxRenderer;
  85408. }());
  85409. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85410. })(BABYLON || (BABYLON = {}));
  85411. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85412. var BABYLON;
  85413. (function (BABYLON) {
  85414. /**
  85415. * Defines a target to use with MorphTargetManager
  85416. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85417. */
  85418. var MorphTarget = /** @class */ (function () {
  85419. /**
  85420. * Creates a new MorphTarget
  85421. * @param name defines the name of the target
  85422. * @param influence defines the influence to use
  85423. */
  85424. function MorphTarget(
  85425. /** defines the name of the target */
  85426. name, influence) {
  85427. if (influence === void 0) { influence = 0; }
  85428. this.name = name;
  85429. /**
  85430. * Gets or sets the list of animations
  85431. */
  85432. this.animations = new Array();
  85433. this._positions = null;
  85434. this._normals = null;
  85435. this._tangents = null;
  85436. /**
  85437. * Observable raised when the influence changes
  85438. */
  85439. this.onInfluenceChanged = new BABYLON.Observable();
  85440. this.influence = influence;
  85441. }
  85442. Object.defineProperty(MorphTarget.prototype, "influence", {
  85443. /**
  85444. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85445. */
  85446. get: function () {
  85447. return this._influence;
  85448. },
  85449. set: function (influence) {
  85450. if (this._influence === influence) {
  85451. return;
  85452. }
  85453. var previous = this._influence;
  85454. this._influence = influence;
  85455. if (this.onInfluenceChanged.hasObservers) {
  85456. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85457. }
  85458. },
  85459. enumerable: true,
  85460. configurable: true
  85461. });
  85462. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85463. /**
  85464. * Gets a boolean defining if the target contains position data
  85465. */
  85466. get: function () {
  85467. return !!this._positions;
  85468. },
  85469. enumerable: true,
  85470. configurable: true
  85471. });
  85472. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85473. /**
  85474. * Gets a boolean defining if the target contains normal data
  85475. */
  85476. get: function () {
  85477. return !!this._normals;
  85478. },
  85479. enumerable: true,
  85480. configurable: true
  85481. });
  85482. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85483. /**
  85484. * Gets a boolean defining if the target contains tangent data
  85485. */
  85486. get: function () {
  85487. return !!this._tangents;
  85488. },
  85489. enumerable: true,
  85490. configurable: true
  85491. });
  85492. /**
  85493. * Affects position data to this target
  85494. * @param data defines the position data to use
  85495. */
  85496. MorphTarget.prototype.setPositions = function (data) {
  85497. this._positions = data;
  85498. };
  85499. /**
  85500. * Gets the position data stored in this target
  85501. * @returns a FloatArray containing the position data (or null if not present)
  85502. */
  85503. MorphTarget.prototype.getPositions = function () {
  85504. return this._positions;
  85505. };
  85506. /**
  85507. * Affects normal data to this target
  85508. * @param data defines the normal data to use
  85509. */
  85510. MorphTarget.prototype.setNormals = function (data) {
  85511. this._normals = data;
  85512. };
  85513. /**
  85514. * Gets the normal data stored in this target
  85515. * @returns a FloatArray containing the normal data (or null if not present)
  85516. */
  85517. MorphTarget.prototype.getNormals = function () {
  85518. return this._normals;
  85519. };
  85520. /**
  85521. * Affects tangent data to this target
  85522. * @param data defines the tangent data to use
  85523. */
  85524. MorphTarget.prototype.setTangents = function (data) {
  85525. this._tangents = data;
  85526. };
  85527. /**
  85528. * Gets the tangent data stored in this target
  85529. * @returns a FloatArray containing the tangent data (or null if not present)
  85530. */
  85531. MorphTarget.prototype.getTangents = function () {
  85532. return this._tangents;
  85533. };
  85534. /**
  85535. * Serializes the current target into a Serialization object
  85536. * @returns the serialized object
  85537. */
  85538. MorphTarget.prototype.serialize = function () {
  85539. var serializationObject = {};
  85540. serializationObject.name = this.name;
  85541. serializationObject.influence = this.influence;
  85542. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85543. if (this.hasNormals) {
  85544. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85545. }
  85546. if (this.hasTangents) {
  85547. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85548. }
  85549. // Animations
  85550. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85551. return serializationObject;
  85552. };
  85553. // Statics
  85554. /**
  85555. * Creates a new target from serialized data
  85556. * @param serializationObject defines the serialized data to use
  85557. * @returns a new MorphTarget
  85558. */
  85559. MorphTarget.Parse = function (serializationObject) {
  85560. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85561. result.setPositions(serializationObject.positions);
  85562. if (serializationObject.normals) {
  85563. result.setNormals(serializationObject.normals);
  85564. }
  85565. if (serializationObject.tangents) {
  85566. result.setTangents(serializationObject.tangents);
  85567. }
  85568. // Animations
  85569. if (serializationObject.animations) {
  85570. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85571. var parsedAnimation = serializationObject.animations[animationIndex];
  85572. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85573. }
  85574. }
  85575. return result;
  85576. };
  85577. /**
  85578. * Creates a MorphTarget from mesh data
  85579. * @param mesh defines the source mesh
  85580. * @param name defines the name to use for the new target
  85581. * @param influence defines the influence to attach to the target
  85582. * @returns a new MorphTarget
  85583. */
  85584. MorphTarget.FromMesh = function (mesh, name, influence) {
  85585. if (!name) {
  85586. name = mesh.name;
  85587. }
  85588. var result = new MorphTarget(name, influence);
  85589. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85590. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85591. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85592. }
  85593. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85594. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85595. }
  85596. return result;
  85597. };
  85598. return MorphTarget;
  85599. }());
  85600. BABYLON.MorphTarget = MorphTarget;
  85601. })(BABYLON || (BABYLON = {}));
  85602. //# sourceMappingURL=babylon.morphTarget.js.map
  85603. var BABYLON;
  85604. (function (BABYLON) {
  85605. /**
  85606. * This class is used to deform meshes using morphing between different targets
  85607. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85608. */
  85609. var MorphTargetManager = /** @class */ (function () {
  85610. /**
  85611. * Creates a new MorphTargetManager
  85612. * @param scene defines the current scene
  85613. */
  85614. function MorphTargetManager(scene) {
  85615. if (scene === void 0) { scene = null; }
  85616. this._targets = new Array();
  85617. this._targetObservable = new Array();
  85618. this._activeTargets = new BABYLON.SmartArray(16);
  85619. this._supportsNormals = false;
  85620. this._supportsTangents = false;
  85621. this._vertexCount = 0;
  85622. this._uniqueId = 0;
  85623. this._tempInfluences = new Array();
  85624. if (!scene) {
  85625. scene = BABYLON.Engine.LastCreatedScene;
  85626. }
  85627. this._scene = scene;
  85628. if (this._scene) {
  85629. this._scene.morphTargetManagers.push(this);
  85630. this._uniqueId = this._scene.getUniqueId();
  85631. }
  85632. }
  85633. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85634. /**
  85635. * Gets the unique ID of this manager
  85636. */
  85637. get: function () {
  85638. return this._uniqueId;
  85639. },
  85640. enumerable: true,
  85641. configurable: true
  85642. });
  85643. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85644. /**
  85645. * Gets the number of vertices handled by this manager
  85646. */
  85647. get: function () {
  85648. return this._vertexCount;
  85649. },
  85650. enumerable: true,
  85651. configurable: true
  85652. });
  85653. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85654. /**
  85655. * Gets a boolean indicating if this manager supports morphing of normals
  85656. */
  85657. get: function () {
  85658. return this._supportsNormals;
  85659. },
  85660. enumerable: true,
  85661. configurable: true
  85662. });
  85663. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85664. /**
  85665. * Gets a boolean indicating if this manager supports morphing of tangents
  85666. */
  85667. get: function () {
  85668. return this._supportsTangents;
  85669. },
  85670. enumerable: true,
  85671. configurable: true
  85672. });
  85673. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85674. /**
  85675. * Gets the number of targets stored in this manager
  85676. */
  85677. get: function () {
  85678. return this._targets.length;
  85679. },
  85680. enumerable: true,
  85681. configurable: true
  85682. });
  85683. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85684. /**
  85685. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85686. */
  85687. get: function () {
  85688. return this._activeTargets.length;
  85689. },
  85690. enumerable: true,
  85691. configurable: true
  85692. });
  85693. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85694. /**
  85695. * Gets the list of influences (one per target)
  85696. */
  85697. get: function () {
  85698. return this._influences;
  85699. },
  85700. enumerable: true,
  85701. configurable: true
  85702. });
  85703. /**
  85704. * Gets the active target at specified index. An active target is a target with an influence > 0
  85705. * @param index defines the index to check
  85706. * @returns the requested target
  85707. */
  85708. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85709. return this._activeTargets.data[index];
  85710. };
  85711. /**
  85712. * Gets the target at specified index
  85713. * @param index defines the index to check
  85714. * @returns the requested target
  85715. */
  85716. MorphTargetManager.prototype.getTarget = function (index) {
  85717. return this._targets[index];
  85718. };
  85719. /**
  85720. * Add a new target to this manager
  85721. * @param target defines the target to add
  85722. */
  85723. MorphTargetManager.prototype.addTarget = function (target) {
  85724. var _this = this;
  85725. this._targets.push(target);
  85726. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85727. _this._syncActiveTargets(needUpdate);
  85728. }));
  85729. this._syncActiveTargets(true);
  85730. };
  85731. /**
  85732. * Removes a target from the manager
  85733. * @param target defines the target to remove
  85734. */
  85735. MorphTargetManager.prototype.removeTarget = function (target) {
  85736. var index = this._targets.indexOf(target);
  85737. if (index >= 0) {
  85738. this._targets.splice(index, 1);
  85739. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85740. this._syncActiveTargets(true);
  85741. }
  85742. };
  85743. /**
  85744. * Serializes the current manager into a Serialization object
  85745. * @returns the serialized object
  85746. */
  85747. MorphTargetManager.prototype.serialize = function () {
  85748. var serializationObject = {};
  85749. serializationObject.id = this.uniqueId;
  85750. serializationObject.targets = [];
  85751. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85752. var target = _a[_i];
  85753. serializationObject.targets.push(target.serialize());
  85754. }
  85755. return serializationObject;
  85756. };
  85757. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85758. var influenceCount = 0;
  85759. this._activeTargets.reset();
  85760. this._supportsNormals = true;
  85761. this._supportsTangents = true;
  85762. this._vertexCount = 0;
  85763. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85764. var target = _a[_i];
  85765. this._activeTargets.push(target);
  85766. this._tempInfluences[influenceCount++] = target.influence;
  85767. var positions = target.getPositions();
  85768. if (positions) {
  85769. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85770. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85771. var vertexCount = positions.length / 3;
  85772. if (this._vertexCount === 0) {
  85773. this._vertexCount = vertexCount;
  85774. }
  85775. else if (this._vertexCount !== vertexCount) {
  85776. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85777. return;
  85778. }
  85779. }
  85780. }
  85781. if (!this._influences || this._influences.length !== influenceCount) {
  85782. this._influences = new Float32Array(influenceCount);
  85783. }
  85784. for (var index = 0; index < influenceCount; index++) {
  85785. this._influences[index] = this._tempInfluences[index];
  85786. }
  85787. if (needUpdate) {
  85788. this.synchronize();
  85789. }
  85790. };
  85791. /**
  85792. * Syncrhonize the targets with all the meshes using this morph target manager
  85793. */
  85794. MorphTargetManager.prototype.synchronize = function () {
  85795. if (!this._scene) {
  85796. return;
  85797. }
  85798. // Flag meshes as dirty to resync with the active targets
  85799. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85800. var mesh = _a[_i];
  85801. if (mesh.morphTargetManager === this) {
  85802. mesh._syncGeometryWithMorphTargetManager();
  85803. }
  85804. }
  85805. };
  85806. // Statics
  85807. /**
  85808. * Creates a new MorphTargetManager from serialized data
  85809. * @param serializationObject defines the serialized data
  85810. * @param scene defines the hosting scene
  85811. * @returns the new MorphTargetManager
  85812. */
  85813. MorphTargetManager.Parse = function (serializationObject, scene) {
  85814. var result = new MorphTargetManager(scene);
  85815. result._uniqueId = serializationObject.id;
  85816. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85817. var targetData = _a[_i];
  85818. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85819. }
  85820. return result;
  85821. };
  85822. return MorphTargetManager;
  85823. }());
  85824. BABYLON.MorphTargetManager = MorphTargetManager;
  85825. })(BABYLON || (BABYLON = {}));
  85826. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85827. var BABYLON;
  85828. (function (BABYLON) {
  85829. var Octree = /** @class */ (function () {
  85830. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85831. if (maxDepth === void 0) { maxDepth = 2; }
  85832. this.maxDepth = maxDepth;
  85833. this.dynamicContent = new Array();
  85834. this._maxBlockCapacity = maxBlockCapacity || 64;
  85835. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85836. this._creationFunc = creationFunc;
  85837. }
  85838. // Methods
  85839. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85840. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85841. };
  85842. Octree.prototype.addMesh = function (entry) {
  85843. for (var index = 0; index < this.blocks.length; index++) {
  85844. var block = this.blocks[index];
  85845. block.addEntry(entry);
  85846. }
  85847. };
  85848. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85849. this._selectionContent.reset();
  85850. for (var index = 0; index < this.blocks.length; index++) {
  85851. var block = this.blocks[index];
  85852. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85853. }
  85854. if (allowDuplicate) {
  85855. this._selectionContent.concat(this.dynamicContent);
  85856. }
  85857. else {
  85858. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85859. }
  85860. return this._selectionContent;
  85861. };
  85862. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85863. this._selectionContent.reset();
  85864. for (var index = 0; index < this.blocks.length; index++) {
  85865. var block = this.blocks[index];
  85866. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85867. }
  85868. if (allowDuplicate) {
  85869. this._selectionContent.concat(this.dynamicContent);
  85870. }
  85871. else {
  85872. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85873. }
  85874. return this._selectionContent;
  85875. };
  85876. Octree.prototype.intersectsRay = function (ray) {
  85877. this._selectionContent.reset();
  85878. for (var index = 0; index < this.blocks.length; index++) {
  85879. var block = this.blocks[index];
  85880. block.intersectsRay(ray, this._selectionContent);
  85881. }
  85882. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85883. return this._selectionContent;
  85884. };
  85885. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85886. target.blocks = new Array();
  85887. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85888. // Segmenting space
  85889. for (var x = 0; x < 2; x++) {
  85890. for (var y = 0; y < 2; y++) {
  85891. for (var z = 0; z < 2; z++) {
  85892. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85893. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85894. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85895. block.addEntries(entries);
  85896. target.blocks.push(block);
  85897. }
  85898. }
  85899. }
  85900. };
  85901. Octree.CreationFuncForMeshes = function (entry, block) {
  85902. var boundingInfo = entry.getBoundingInfo();
  85903. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85904. block.entries.push(entry);
  85905. }
  85906. };
  85907. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85908. var boundingInfo = entry.getBoundingInfo();
  85909. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85910. block.entries.push(entry);
  85911. }
  85912. };
  85913. return Octree;
  85914. }());
  85915. BABYLON.Octree = Octree;
  85916. })(BABYLON || (BABYLON = {}));
  85917. //# sourceMappingURL=babylon.octree.js.map
  85918. var BABYLON;
  85919. (function (BABYLON) {
  85920. var OctreeBlock = /** @class */ (function () {
  85921. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85922. this.entries = new Array();
  85923. this._boundingVectors = new Array();
  85924. this._capacity = capacity;
  85925. this._depth = depth;
  85926. this._maxDepth = maxDepth;
  85927. this._creationFunc = creationFunc;
  85928. this._minPoint = minPoint;
  85929. this._maxPoint = maxPoint;
  85930. this._boundingVectors.push(minPoint.clone());
  85931. this._boundingVectors.push(maxPoint.clone());
  85932. this._boundingVectors.push(minPoint.clone());
  85933. this._boundingVectors[2].x = maxPoint.x;
  85934. this._boundingVectors.push(minPoint.clone());
  85935. this._boundingVectors[3].y = maxPoint.y;
  85936. this._boundingVectors.push(minPoint.clone());
  85937. this._boundingVectors[4].z = maxPoint.z;
  85938. this._boundingVectors.push(maxPoint.clone());
  85939. this._boundingVectors[5].z = minPoint.z;
  85940. this._boundingVectors.push(maxPoint.clone());
  85941. this._boundingVectors[6].x = minPoint.x;
  85942. this._boundingVectors.push(maxPoint.clone());
  85943. this._boundingVectors[7].y = minPoint.y;
  85944. }
  85945. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  85946. // Property
  85947. get: function () {
  85948. return this._capacity;
  85949. },
  85950. enumerable: true,
  85951. configurable: true
  85952. });
  85953. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  85954. get: function () {
  85955. return this._minPoint;
  85956. },
  85957. enumerable: true,
  85958. configurable: true
  85959. });
  85960. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  85961. get: function () {
  85962. return this._maxPoint;
  85963. },
  85964. enumerable: true,
  85965. configurable: true
  85966. });
  85967. // Methods
  85968. OctreeBlock.prototype.addEntry = function (entry) {
  85969. if (this.blocks) {
  85970. for (var index = 0; index < this.blocks.length; index++) {
  85971. var block = this.blocks[index];
  85972. block.addEntry(entry);
  85973. }
  85974. return;
  85975. }
  85976. this._creationFunc(entry, this);
  85977. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  85978. this.createInnerBlocks();
  85979. }
  85980. };
  85981. OctreeBlock.prototype.addEntries = function (entries) {
  85982. for (var index = 0; index < entries.length; index++) {
  85983. var mesh = entries[index];
  85984. this.addEntry(mesh);
  85985. }
  85986. };
  85987. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  85988. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  85989. if (this.blocks) {
  85990. for (var index = 0; index < this.blocks.length; index++) {
  85991. var block = this.blocks[index];
  85992. block.select(frustumPlanes, selection, allowDuplicate);
  85993. }
  85994. return;
  85995. }
  85996. if (allowDuplicate) {
  85997. selection.concat(this.entries);
  85998. }
  85999. else {
  86000. selection.concatWithNoDuplicate(this.entries);
  86001. }
  86002. }
  86003. };
  86004. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86005. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86006. if (this.blocks) {
  86007. for (var index = 0; index < this.blocks.length; index++) {
  86008. var block = this.blocks[index];
  86009. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86010. }
  86011. return;
  86012. }
  86013. if (allowDuplicate) {
  86014. selection.concat(this.entries);
  86015. }
  86016. else {
  86017. selection.concatWithNoDuplicate(this.entries);
  86018. }
  86019. }
  86020. };
  86021. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86022. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86023. if (this.blocks) {
  86024. for (var index = 0; index < this.blocks.length; index++) {
  86025. var block = this.blocks[index];
  86026. block.intersectsRay(ray, selection);
  86027. }
  86028. return;
  86029. }
  86030. selection.concatWithNoDuplicate(this.entries);
  86031. }
  86032. };
  86033. OctreeBlock.prototype.createInnerBlocks = function () {
  86034. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86035. };
  86036. return OctreeBlock;
  86037. }());
  86038. BABYLON.OctreeBlock = OctreeBlock;
  86039. })(BABYLON || (BABYLON = {}));
  86040. //# sourceMappingURL=babylon.octreeBlock.js.map
  86041. var BABYLON;
  86042. (function (BABYLON) {
  86043. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86044. __extends(VRDistortionCorrectionPostProcess, _super);
  86045. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86046. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86047. 'LensCenter',
  86048. 'Scale',
  86049. 'ScaleIn',
  86050. 'HmdWarpParam'
  86051. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86052. _this._isRightEye = isRightEye;
  86053. _this._distortionFactors = vrMetrics.distortionK;
  86054. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86055. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86056. _this.adaptScaleToCurrentViewport = true;
  86057. _this.onSizeChangedObservable.add(function () {
  86058. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86059. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86060. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86061. });
  86062. _this.onApplyObservable.add(function (effect) {
  86063. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86064. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86065. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86066. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86067. });
  86068. return _this;
  86069. }
  86070. return VRDistortionCorrectionPostProcess;
  86071. }(BABYLON.PostProcess));
  86072. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86073. })(BABYLON || (BABYLON = {}));
  86074. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86075. var BABYLON;
  86076. (function (BABYLON) {
  86077. /**
  86078. * Postprocess used to generate anaglyphic rendering
  86079. */
  86080. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86081. __extends(AnaglyphPostProcess, _super);
  86082. /**
  86083. * Creates a new AnaglyphPostProcess
  86084. * @param name defines postprocess name
  86085. * @param options defines creation options or target ratio scale
  86086. * @param rigCameras defines cameras using this postprocess
  86087. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86088. * @param engine defines hosting engine
  86089. * @param reusable defines if the postprocess will be reused multiple times per frame
  86090. */
  86091. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86092. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86093. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86094. _this.onApplyObservable.add(function (effect) {
  86095. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86096. });
  86097. return _this;
  86098. }
  86099. return AnaglyphPostProcess;
  86100. }(BABYLON.PostProcess));
  86101. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86102. })(BABYLON || (BABYLON = {}));
  86103. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86104. var BABYLON;
  86105. (function (BABYLON) {
  86106. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86107. __extends(StereoscopicInterlacePostProcess, _super);
  86108. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86109. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86110. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86111. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86112. _this.onSizeChangedObservable.add(function () {
  86113. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86114. });
  86115. _this.onApplyObservable.add(function (effect) {
  86116. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86117. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86118. });
  86119. return _this;
  86120. }
  86121. return StereoscopicInterlacePostProcess;
  86122. }(BABYLON.PostProcess));
  86123. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86124. })(BABYLON || (BABYLON = {}));
  86125. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86126. var BABYLON;
  86127. (function (BABYLON) {
  86128. /**
  86129. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86130. * Screen rotation is taken into account.
  86131. */
  86132. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86133. function FreeCameraDeviceOrientationInput() {
  86134. var _this = this;
  86135. this._screenOrientationAngle = 0;
  86136. this._screenQuaternion = new BABYLON.Quaternion();
  86137. this._alpha = 0;
  86138. this._beta = 0;
  86139. this._gamma = 0;
  86140. this._orientationChanged = function () {
  86141. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86142. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86143. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86144. };
  86145. this._deviceOrientation = function (evt) {
  86146. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86147. _this._beta = evt.beta !== null ? evt.beta : 0;
  86148. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86149. };
  86150. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86151. this._orientationChanged();
  86152. }
  86153. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86154. get: function () {
  86155. return this._camera;
  86156. },
  86157. set: function (camera) {
  86158. this._camera = camera;
  86159. if (this._camera != null && !this._camera.rotationQuaternion) {
  86160. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86161. }
  86162. },
  86163. enumerable: true,
  86164. configurable: true
  86165. });
  86166. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86167. window.addEventListener("orientationchange", this._orientationChanged);
  86168. window.addEventListener("deviceorientation", this._deviceOrientation);
  86169. //In certain cases, the attach control is called AFTER orientation was changed,
  86170. //So this is needed.
  86171. this._orientationChanged();
  86172. };
  86173. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86174. window.removeEventListener("orientationchange", this._orientationChanged);
  86175. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86176. };
  86177. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86178. //if no device orientation provided, don't update the rotation.
  86179. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86180. if (!this._alpha)
  86181. return;
  86182. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86183. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86184. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86185. //Mirror on XY Plane
  86186. this._camera.rotationQuaternion.z *= -1;
  86187. this._camera.rotationQuaternion.w *= -1;
  86188. };
  86189. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86190. return "FreeCameraDeviceOrientationInput";
  86191. };
  86192. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86193. return "deviceOrientation";
  86194. };
  86195. return FreeCameraDeviceOrientationInput;
  86196. }());
  86197. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86198. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86199. })(BABYLON || (BABYLON = {}));
  86200. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86201. var BABYLON;
  86202. (function (BABYLON) {
  86203. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86204. function ArcRotateCameraVRDeviceOrientationInput() {
  86205. this.alphaCorrection = 1;
  86206. this.betaCorrection = 1;
  86207. this.gammaCorrection = 1;
  86208. this._alpha = 0;
  86209. this._gamma = 0;
  86210. this._dirty = false;
  86211. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86212. }
  86213. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86214. this.camera.attachControl(element, noPreventDefault);
  86215. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86216. };
  86217. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86218. if (evt.alpha !== null) {
  86219. this._alpha = +evt.alpha | 0;
  86220. }
  86221. if (evt.gamma !== null) {
  86222. this._gamma = +evt.gamma | 0;
  86223. }
  86224. this._dirty = true;
  86225. };
  86226. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86227. if (this._dirty) {
  86228. this._dirty = false;
  86229. if (this._gamma < 0) {
  86230. this._gamma = 180 + this._gamma;
  86231. }
  86232. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86233. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86234. }
  86235. };
  86236. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86237. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86238. };
  86239. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86240. return "ArcRotateCameraVRDeviceOrientationInput";
  86241. };
  86242. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86243. return "VRDeviceOrientation";
  86244. };
  86245. return ArcRotateCameraVRDeviceOrientationInput;
  86246. }());
  86247. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86248. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86249. })(BABYLON || (BABYLON = {}));
  86250. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86251. var BABYLON;
  86252. (function (BABYLON) {
  86253. var VRCameraMetrics = /** @class */ (function () {
  86254. function VRCameraMetrics() {
  86255. this.compensateDistortion = true;
  86256. }
  86257. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86258. get: function () {
  86259. return this.hResolution / (2 * this.vResolution);
  86260. },
  86261. enumerable: true,
  86262. configurable: true
  86263. });
  86264. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86265. get: function () {
  86266. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86267. },
  86268. enumerable: true,
  86269. configurable: true
  86270. });
  86271. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86272. get: function () {
  86273. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86274. var h = (4 * meters) / this.hScreenSize;
  86275. return BABYLON.Matrix.Translation(h, 0, 0);
  86276. },
  86277. enumerable: true,
  86278. configurable: true
  86279. });
  86280. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86281. get: function () {
  86282. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86283. var h = (4 * meters) / this.hScreenSize;
  86284. return BABYLON.Matrix.Translation(-h, 0, 0);
  86285. },
  86286. enumerable: true,
  86287. configurable: true
  86288. });
  86289. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86290. get: function () {
  86291. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86292. },
  86293. enumerable: true,
  86294. configurable: true
  86295. });
  86296. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86297. get: function () {
  86298. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86299. },
  86300. enumerable: true,
  86301. configurable: true
  86302. });
  86303. VRCameraMetrics.GetDefault = function () {
  86304. var result = new VRCameraMetrics();
  86305. result.hResolution = 1280;
  86306. result.vResolution = 800;
  86307. result.hScreenSize = 0.149759993;
  86308. result.vScreenSize = 0.0935999975;
  86309. result.vScreenCenter = 0.0467999987;
  86310. result.eyeToScreenDistance = 0.0410000011;
  86311. result.lensSeparationDistance = 0.0635000020;
  86312. result.interpupillaryDistance = 0.0640000030;
  86313. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86314. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86315. result.postProcessScaleFactor = 1.714605507808412;
  86316. result.lensCenterOffset = 0.151976421;
  86317. return result;
  86318. };
  86319. return VRCameraMetrics;
  86320. }());
  86321. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86322. })(BABYLON || (BABYLON = {}));
  86323. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86324. var BABYLON;
  86325. (function (BABYLON) {
  86326. /**
  86327. * This represents a WebVR camera.
  86328. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86329. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86330. */
  86331. var WebVRFreeCamera = /** @class */ (function (_super) {
  86332. __extends(WebVRFreeCamera, _super);
  86333. /**
  86334. * Instantiates a WebVRFreeCamera.
  86335. * @param name The name of the WebVRFreeCamera
  86336. * @param position The starting anchor position for the camera
  86337. * @param scene The scene the camera belongs to
  86338. * @param webVROptions a set of customizable options for the webVRCamera
  86339. */
  86340. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86341. if (webVROptions === void 0) { webVROptions = {}; }
  86342. var _this = _super.call(this, name, position, scene) || this;
  86343. _this.webVROptions = webVROptions;
  86344. /**
  86345. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86346. */
  86347. _this._vrDevice = null;
  86348. /**
  86349. * The rawPose of the vrDevice.
  86350. */
  86351. _this.rawPose = null;
  86352. _this._specsVersion = "1.1";
  86353. _this._attached = false;
  86354. _this._descendants = [];
  86355. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86356. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86357. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86358. _this._standingMatrix = null;
  86359. /**
  86360. * Represents device position in babylon space.
  86361. */
  86362. _this.devicePosition = BABYLON.Vector3.Zero();
  86363. /**
  86364. * Represents device rotation in babylon space.
  86365. */
  86366. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86367. /**
  86368. * The scale of the device to be used when translating from device space to babylon space.
  86369. */
  86370. _this.deviceScaleFactor = 1;
  86371. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86372. _this._worldToDevice = BABYLON.Matrix.Identity();
  86373. /**
  86374. * References to the webVR controllers for the vrDevice.
  86375. */
  86376. _this.controllers = [];
  86377. /**
  86378. * Emits an event when a controller is attached.
  86379. */
  86380. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86381. /**
  86382. * Emits an event when a controller's mesh has been loaded;
  86383. */
  86384. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86385. /**
  86386. * If the rig cameras be used as parent instead of this camera.
  86387. */
  86388. _this.rigParenting = true;
  86389. _this._defaultHeight = undefined;
  86390. _this._workingVector = BABYLON.Vector3.Zero();
  86391. _this._oneVector = BABYLON.Vector3.One();
  86392. _this._workingMatrix = BABYLON.Matrix.Identity();
  86393. _this._cache.position = BABYLON.Vector3.Zero();
  86394. if (webVROptions.defaultHeight) {
  86395. _this._defaultHeight = webVROptions.defaultHeight;
  86396. _this.position.y = _this._defaultHeight;
  86397. }
  86398. _this.minZ = 0.1;
  86399. //legacy support - the compensation boolean was removed.
  86400. if (arguments.length === 5) {
  86401. _this.webVROptions = arguments[4];
  86402. }
  86403. // default webVR options
  86404. if (_this.webVROptions.trackPosition == undefined) {
  86405. _this.webVROptions.trackPosition = true;
  86406. }
  86407. if (_this.webVROptions.controllerMeshes == undefined) {
  86408. _this.webVROptions.controllerMeshes = true;
  86409. }
  86410. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86411. _this.webVROptions.defaultLightingOnControllers = true;
  86412. }
  86413. _this.rotationQuaternion = new BABYLON.Quaternion();
  86414. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86415. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86416. }
  86417. //enable VR
  86418. var engine = _this.getEngine();
  86419. _this._onVREnabled = function (success) { if (success) {
  86420. _this.initControllers();
  86421. } };
  86422. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86423. engine.initWebVR().add(function (event) {
  86424. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86425. return;
  86426. }
  86427. _this._vrDevice = event.vrDisplay;
  86428. //reset the rig parameters.
  86429. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86430. if (_this._attached) {
  86431. _this.getEngine().enableVR();
  86432. }
  86433. });
  86434. if (typeof (VRFrameData) !== "undefined")
  86435. _this._frameData = new VRFrameData();
  86436. /**
  86437. * The idea behind the following lines:
  86438. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86439. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86440. * the second will not show it correctly.
  86441. *
  86442. * To solve this - each object that has the camera as parent will be added to a protected array.
  86443. * When the rig camera renders, it will take this array and set all of those to be its children.
  86444. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86445. * Amazing!
  86446. */
  86447. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86448. if (camera.parent === _this && _this.rigParenting) {
  86449. _this._descendants = _this.getDescendants(true, function (n) {
  86450. // don't take the cameras or the controllers!
  86451. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86452. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86453. return !isController && !isRigCamera;
  86454. });
  86455. _this._descendants.forEach(function (node) {
  86456. node.parent = camera;
  86457. });
  86458. }
  86459. });
  86460. scene.onAfterCameraRenderObservable.add(function (camera) {
  86461. if (camera.parent === _this && _this.rigParenting) {
  86462. _this._descendants.forEach(function (node) {
  86463. node.parent = _this;
  86464. });
  86465. }
  86466. });
  86467. return _this;
  86468. }
  86469. /**
  86470. * Gets the device distance from the ground in meters.
  86471. * @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.
  86472. */
  86473. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86474. if (this._standingMatrix) {
  86475. // Add standing matrix offset to get real offset from ground in room
  86476. this._standingMatrix.getTranslationToRef(this._workingVector);
  86477. return this._deviceRoomPosition.y + this._workingVector.y;
  86478. }
  86479. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86480. return this._defaultHeight || 0;
  86481. };
  86482. /**
  86483. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86484. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86485. */
  86486. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86487. var _this = this;
  86488. if (callback === void 0) { callback = function (bool) { }; }
  86489. // Use standing matrix if available
  86490. this.getEngine().initWebVRAsync().then(function (result) {
  86491. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86492. callback(false);
  86493. }
  86494. else {
  86495. _this._standingMatrix = new BABYLON.Matrix();
  86496. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86497. if (!_this.getScene().useRightHandedSystem) {
  86498. [2, 6, 8, 9, 14].forEach(function (num) {
  86499. if (_this._standingMatrix) {
  86500. _this._standingMatrix.m[num] *= -1;
  86501. }
  86502. });
  86503. }
  86504. callback(true);
  86505. }
  86506. });
  86507. };
  86508. /**
  86509. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86510. * @returns A promise with a boolean set to if the standing matrix is supported.
  86511. */
  86512. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86513. var _this = this;
  86514. return new Promise(function (res, rej) {
  86515. _this.useStandingMatrix(function (supported) {
  86516. res(supported);
  86517. });
  86518. });
  86519. };
  86520. /**
  86521. * Disposes the camera
  86522. */
  86523. WebVRFreeCamera.prototype.dispose = function () {
  86524. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86525. _super.prototype.dispose.call(this);
  86526. };
  86527. /**
  86528. * Gets a vrController by name.
  86529. * @param name The name of the controller to retreive
  86530. * @returns the controller matching the name specified or null if not found
  86531. */
  86532. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86533. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86534. var gp = _a[_i];
  86535. if (gp.hand === name) {
  86536. return gp;
  86537. }
  86538. }
  86539. return null;
  86540. };
  86541. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86542. /**
  86543. * The controller corrisponding to the users left hand.
  86544. */
  86545. get: function () {
  86546. if (!this._leftController) {
  86547. this._leftController = this.getControllerByName("left");
  86548. }
  86549. return this._leftController;
  86550. },
  86551. enumerable: true,
  86552. configurable: true
  86553. });
  86554. ;
  86555. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86556. /**
  86557. * The controller corrisponding to the users right hand.
  86558. */
  86559. get: function () {
  86560. if (!this._rightController) {
  86561. this._rightController = this.getControllerByName("right");
  86562. }
  86563. return this._rightController;
  86564. },
  86565. enumerable: true,
  86566. configurable: true
  86567. });
  86568. ;
  86569. /**
  86570. * Casts a ray forward from the vrCamera's gaze.
  86571. * @param length Length of the ray (default: 100)
  86572. * @returns the ray corrisponding to the gaze
  86573. */
  86574. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86575. if (length === void 0) { length = 100; }
  86576. if (this.leftCamera) {
  86577. // Use left eye to avoid computation to compute center on every call
  86578. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86579. }
  86580. else {
  86581. return _super.prototype.getForwardRay.call(this, length);
  86582. }
  86583. };
  86584. /**
  86585. * Updates the camera based on device's frame data
  86586. */
  86587. WebVRFreeCamera.prototype._checkInputs = function () {
  86588. if (this._vrDevice && this._vrDevice.isPresenting) {
  86589. this._vrDevice.getFrameData(this._frameData);
  86590. this.updateFromDevice(this._frameData.pose);
  86591. }
  86592. _super.prototype._checkInputs.call(this);
  86593. };
  86594. /**
  86595. * Updates the poseControlled values based on the input device pose.
  86596. * @param poseData Pose coming from the device
  86597. */
  86598. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86599. if (poseData && poseData.orientation) {
  86600. this.rawPose = poseData;
  86601. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86602. if (this.getScene().useRightHandedSystem) {
  86603. this._deviceRoomRotationQuaternion.z *= -1;
  86604. this._deviceRoomRotationQuaternion.w *= -1;
  86605. }
  86606. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86607. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86608. if (this.getScene().useRightHandedSystem) {
  86609. this._deviceRoomPosition.z *= -1;
  86610. }
  86611. }
  86612. }
  86613. };
  86614. /**
  86615. * WebVR's attach control will start broadcasting frames to the device.
  86616. * Note that in certain browsers (chrome for example) this function must be called
  86617. * within a user-interaction callback. Example:
  86618. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86619. *
  86620. * @param element html element to attach the vrDevice to
  86621. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86622. */
  86623. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86624. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86625. this._attached = true;
  86626. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86627. if (this._vrDevice) {
  86628. this.getEngine().enableVR();
  86629. }
  86630. };
  86631. /**
  86632. * Detaches the camera from the html element and disables VR
  86633. *
  86634. * @param element html element to detach from
  86635. */
  86636. WebVRFreeCamera.prototype.detachControl = function (element) {
  86637. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86638. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86639. _super.prototype.detachControl.call(this, element);
  86640. this._attached = false;
  86641. this.getEngine().disableVR();
  86642. };
  86643. /**
  86644. * @returns the name of this class
  86645. */
  86646. WebVRFreeCamera.prototype.getClassName = function () {
  86647. return "WebVRFreeCamera";
  86648. };
  86649. /**
  86650. * Calls resetPose on the vrDisplay
  86651. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86652. */
  86653. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86654. //uses the vrDisplay's "resetPose()".
  86655. //pitch and roll won't be affected.
  86656. this._vrDevice.resetPose();
  86657. };
  86658. /**
  86659. * Updates the rig cameras (left and right eye)
  86660. */
  86661. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86662. var camLeft = this._rigCameras[0];
  86663. var camRight = this._rigCameras[1];
  86664. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86665. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86666. camLeft.position.copyFrom(this._deviceRoomPosition);
  86667. camRight.position.copyFrom(this._deviceRoomPosition);
  86668. };
  86669. /**
  86670. * Updates the cached values of the camera
  86671. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86672. */
  86673. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86674. var _this = this;
  86675. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86676. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86677. if (!this.updateCacheCalled) {
  86678. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86679. this.updateCacheCalled = true;
  86680. this.update();
  86681. }
  86682. // Set working vector to the device position in room space rotated by the new rotation
  86683. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86684. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86685. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86686. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86687. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86688. // Add translation from anchor position
  86689. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86690. this._workingVector.addInPlace(this.position);
  86691. this._workingVector.subtractInPlace(this._cache.position);
  86692. this._deviceToWorld.setTranslation(this._workingVector);
  86693. // Set an inverted matrix to be used when updating the camera
  86694. this._deviceToWorld.invertToRef(this._worldToDevice);
  86695. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86696. this.controllers.forEach(function (controller) {
  86697. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86698. controller.update();
  86699. });
  86700. }
  86701. if (!ignoreParentClass) {
  86702. _super.prototype._updateCache.call(this);
  86703. }
  86704. this.updateCacheCalled = false;
  86705. };
  86706. /**
  86707. * Updates the current device position and rotation in the babylon world
  86708. */
  86709. WebVRFreeCamera.prototype.update = function () {
  86710. // Get current device position in babylon world
  86711. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86712. // Get current device rotation in babylon world
  86713. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86714. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86715. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86716. _super.prototype.update.call(this);
  86717. };
  86718. /**
  86719. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86720. * @returns an identity matrix
  86721. */
  86722. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86723. return BABYLON.Matrix.Identity();
  86724. };
  86725. /**
  86726. * This function is called by the two RIG cameras.
  86727. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86728. */
  86729. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86730. var _this = this;
  86731. // Update the parent camera prior to using a child camera to avoid desynchronization
  86732. var parentCamera = this._cameraRigParams["parentCamera"];
  86733. parentCamera._updateCache();
  86734. //WebVR 1.1
  86735. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86736. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86737. if (!this.getScene().useRightHandedSystem) {
  86738. [2, 6, 8, 9, 14].forEach(function (num) {
  86739. _this._webvrViewMatrix.m[num] *= -1;
  86740. });
  86741. }
  86742. // update the camera rotation matrix
  86743. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86744. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86745. // Computing target and final matrix
  86746. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86747. // should the view matrix be updated with scale and position offset?
  86748. if (parentCamera.deviceScaleFactor !== 1) {
  86749. this._webvrViewMatrix.invert();
  86750. // scale the position, if set
  86751. if (parentCamera.deviceScaleFactor) {
  86752. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86753. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86754. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86755. }
  86756. this._webvrViewMatrix.invert();
  86757. }
  86758. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86759. // Compute global position
  86760. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86761. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86762. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86763. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86764. this._markSyncedWithParent();
  86765. return this._webvrViewMatrix;
  86766. };
  86767. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86768. var _this = this;
  86769. var parentCamera = this.parent;
  86770. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86771. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86772. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86773. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86774. //babylon compatible matrix
  86775. if (!this.getScene().useRightHandedSystem) {
  86776. [8, 9, 10, 11].forEach(function (num) {
  86777. _this._projectionMatrix.m[num] *= -1;
  86778. });
  86779. }
  86780. return this._projectionMatrix;
  86781. };
  86782. /**
  86783. * Initializes the controllers and their meshes
  86784. */
  86785. WebVRFreeCamera.prototype.initControllers = function () {
  86786. var _this = this;
  86787. this.controllers = [];
  86788. var manager = this.getScene().gamepadManager;
  86789. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86790. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86791. var webVrController = gamepad;
  86792. if (webVrController.defaultModel) {
  86793. webVrController.defaultModel.setEnabled(false);
  86794. }
  86795. if (webVrController.hand === "right") {
  86796. _this._rightController = null;
  86797. }
  86798. if (webVrController.hand === "left") {
  86799. _this._leftController = null;
  86800. }
  86801. var controllerIndex = _this.controllers.indexOf(webVrController);
  86802. if (controllerIndex !== -1) {
  86803. _this.controllers.splice(controllerIndex, 1);
  86804. }
  86805. }
  86806. });
  86807. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86808. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86809. var webVrController_1 = gamepad;
  86810. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86811. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86812. if (_this.webVROptions.controllerMeshes) {
  86813. if (webVrController_1.defaultModel) {
  86814. webVrController_1.defaultModel.setEnabled(true);
  86815. }
  86816. else {
  86817. // Load the meshes
  86818. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86819. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86820. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86821. if (_this.webVROptions.defaultLightingOnControllers) {
  86822. if (!_this._lightOnControllers) {
  86823. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86824. }
  86825. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86826. var children = mesh.getChildren();
  86827. if (children.length !== 0) {
  86828. children.forEach(function (mesh) {
  86829. light.includedOnlyMeshes.push(mesh);
  86830. activateLightOnSubMeshes_1(mesh, light);
  86831. });
  86832. }
  86833. };
  86834. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86835. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86836. }
  86837. });
  86838. }
  86839. }
  86840. webVrController_1.attachToPoseControlledCamera(_this);
  86841. // since this is async - sanity check. Is the controller already stored?
  86842. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86843. //add to the controllers array
  86844. _this.controllers.push(webVrController_1);
  86845. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86846. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86847. // So we're overriding setting left & right manually to be sure
  86848. var firstViveWandDetected = false;
  86849. for (var i = 0; i < _this.controllers.length; i++) {
  86850. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86851. if (!firstViveWandDetected) {
  86852. firstViveWandDetected = true;
  86853. _this.controllers[i].hand = "left";
  86854. }
  86855. else {
  86856. _this.controllers[i].hand = "right";
  86857. }
  86858. }
  86859. }
  86860. //did we find enough controllers? Great! let the developer know.
  86861. if (_this.controllers.length >= 2) {
  86862. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86863. }
  86864. }
  86865. }
  86866. });
  86867. };
  86868. return WebVRFreeCamera;
  86869. }(BABYLON.FreeCamera));
  86870. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86871. })(BABYLON || (BABYLON = {}));
  86872. //# sourceMappingURL=babylon.webVRCamera.js.map
  86873. var BABYLON;
  86874. (function (BABYLON) {
  86875. // We're mainly based on the logic defined into the FreeCamera code
  86876. /**
  86877. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86878. * being tilted forward or back and left or right.
  86879. */
  86880. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86881. __extends(DeviceOrientationCamera, _super);
  86882. /**
  86883. * Creates a new device orientation camera
  86884. * @param name The name of the camera
  86885. * @param position The start position camera
  86886. * @param scene The scene the camera belongs to
  86887. */
  86888. function DeviceOrientationCamera(name, position, scene) {
  86889. var _this = _super.call(this, name, position, scene) || this;
  86890. _this._quaternionCache = new BABYLON.Quaternion();
  86891. _this.inputs.addDeviceOrientation();
  86892. return _this;
  86893. }
  86894. /**
  86895. * Gets the current instance class name ("DeviceOrientationCamera").
  86896. * This helps avoiding instanceof at run time.
  86897. * @returns the class name
  86898. */
  86899. DeviceOrientationCamera.prototype.getClassName = function () {
  86900. return "DeviceOrientationCamera";
  86901. };
  86902. /**
  86903. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86904. */
  86905. DeviceOrientationCamera.prototype._checkInputs = function () {
  86906. _super.prototype._checkInputs.call(this);
  86907. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86908. if (this._initialQuaternion) {
  86909. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86910. }
  86911. };
  86912. /**
  86913. * Reset the camera to its default orientation on the specified axis only.
  86914. * @param axis The axis to reset
  86915. */
  86916. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86917. var _this = this;
  86918. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86919. //can only work if this camera has a rotation quaternion already.
  86920. if (!this.rotationQuaternion)
  86921. return;
  86922. if (!this._initialQuaternion) {
  86923. this._initialQuaternion = new BABYLON.Quaternion();
  86924. }
  86925. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86926. ['x', 'y', 'z'].forEach(function (axisName) {
  86927. if (!axis[axisName]) {
  86928. _this._initialQuaternion[axisName] = 0;
  86929. }
  86930. else {
  86931. _this._initialQuaternion[axisName] *= -1;
  86932. }
  86933. });
  86934. this._initialQuaternion.normalize();
  86935. //force rotation update
  86936. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86937. };
  86938. return DeviceOrientationCamera;
  86939. }(BABYLON.FreeCamera));
  86940. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  86941. })(BABYLON || (BABYLON = {}));
  86942. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  86943. var BABYLON;
  86944. (function (BABYLON) {
  86945. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  86946. __extends(VRDeviceOrientationFreeCamera, _super);
  86947. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86948. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86949. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86950. var _this = _super.call(this, name, position, scene) || this;
  86951. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86952. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86953. return _this;
  86954. }
  86955. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  86956. return "VRDeviceOrientationFreeCamera";
  86957. };
  86958. return VRDeviceOrientationFreeCamera;
  86959. }(BABYLON.DeviceOrientationCamera));
  86960. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  86961. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  86962. __extends(VRDeviceOrientationGamepadCamera, _super);
  86963. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86964. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86965. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86966. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  86967. _this.inputs.addGamepad();
  86968. return _this;
  86969. }
  86970. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  86971. return "VRDeviceOrientationGamepadCamera";
  86972. };
  86973. return VRDeviceOrientationGamepadCamera;
  86974. }(VRDeviceOrientationFreeCamera));
  86975. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  86976. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  86977. __extends(VRDeviceOrientationArcRotateCamera, _super);
  86978. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  86979. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86980. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86981. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86982. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86983. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86984. _this.inputs.addVRDeviceOrientation();
  86985. return _this;
  86986. }
  86987. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  86988. return "VRDeviceOrientationArcRotateCamera";
  86989. };
  86990. return VRDeviceOrientationArcRotateCamera;
  86991. }(BABYLON.ArcRotateCamera));
  86992. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  86993. })(BABYLON || (BABYLON = {}));
  86994. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  86995. var BABYLON;
  86996. (function (BABYLON) {
  86997. /**
  86998. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  86999. */
  87000. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87001. __extends(AnaglyphFreeCamera, _super);
  87002. /**
  87003. * Creates a new AnaglyphFreeCamera
  87004. * @param name defines camera name
  87005. * @param position defines initial position
  87006. * @param interaxialDistance defines distance between each color axis
  87007. * @param scene defines the hosting scene
  87008. */
  87009. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87010. var _this = _super.call(this, name, position, scene) || this;
  87011. _this.interaxialDistance = interaxialDistance;
  87012. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87013. return _this;
  87014. }
  87015. /**
  87016. * Gets camera class name
  87017. * @returns AnaglyphFreeCamera
  87018. */
  87019. AnaglyphFreeCamera.prototype.getClassName = function () {
  87020. return "AnaglyphFreeCamera";
  87021. };
  87022. return AnaglyphFreeCamera;
  87023. }(BABYLON.FreeCamera));
  87024. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87025. /**
  87026. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87027. */
  87028. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87029. __extends(AnaglyphArcRotateCamera, _super);
  87030. /**
  87031. * Creates a new AnaglyphArcRotateCamera
  87032. * @param name defines camera name
  87033. * @param alpha defines alpha angle (in radians)
  87034. * @param beta defines beta angle (in radians)
  87035. * @param radius defines radius
  87036. * @param target defines camera target
  87037. * @param interaxialDistance defines distance between each color axis
  87038. * @param scene defines the hosting scene
  87039. */
  87040. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87041. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87042. _this.interaxialDistance = interaxialDistance;
  87043. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87044. return _this;
  87045. }
  87046. /**
  87047. * Gets camera class name
  87048. * @returns AnaglyphArcRotateCamera
  87049. */
  87050. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87051. return "AnaglyphArcRotateCamera";
  87052. };
  87053. return AnaglyphArcRotateCamera;
  87054. }(BABYLON.ArcRotateCamera));
  87055. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87056. /**
  87057. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87058. */
  87059. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87060. __extends(AnaglyphGamepadCamera, _super);
  87061. /**
  87062. * Creates a new AnaglyphGamepadCamera
  87063. * @param name defines camera name
  87064. * @param position defines initial position
  87065. * @param interaxialDistance defines distance between each color axis
  87066. * @param scene defines the hosting scene
  87067. */
  87068. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87069. var _this = _super.call(this, name, position, scene) || this;
  87070. _this.interaxialDistance = interaxialDistance;
  87071. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87072. return _this;
  87073. }
  87074. /**
  87075. * Gets camera class name
  87076. * @returns AnaglyphGamepadCamera
  87077. */
  87078. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87079. return "AnaglyphGamepadCamera";
  87080. };
  87081. return AnaglyphGamepadCamera;
  87082. }(BABYLON.GamepadCamera));
  87083. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87084. /**
  87085. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87086. */
  87087. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87088. __extends(AnaglyphUniversalCamera, _super);
  87089. /**
  87090. * Creates a new AnaglyphUniversalCamera
  87091. * @param name defines camera name
  87092. * @param position defines initial position
  87093. * @param interaxialDistance defines distance between each color axis
  87094. * @param scene defines the hosting scene
  87095. */
  87096. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87097. var _this = _super.call(this, name, position, scene) || this;
  87098. _this.interaxialDistance = interaxialDistance;
  87099. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87100. return _this;
  87101. }
  87102. /**
  87103. * Gets camera class name
  87104. * @returns AnaglyphUniversalCamera
  87105. */
  87106. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87107. return "AnaglyphUniversalCamera";
  87108. };
  87109. return AnaglyphUniversalCamera;
  87110. }(BABYLON.UniversalCamera));
  87111. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87112. /**
  87113. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87114. */
  87115. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87116. __extends(StereoscopicFreeCamera, _super);
  87117. /**
  87118. * Creates a new StereoscopicFreeCamera
  87119. * @param name defines camera name
  87120. * @param position defines initial position
  87121. * @param interaxialDistance defines distance between each color axis
  87122. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87123. * @param scene defines the hosting scene
  87124. */
  87125. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87126. var _this = _super.call(this, name, position, scene) || this;
  87127. _this.interaxialDistance = interaxialDistance;
  87128. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87129. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87130. return _this;
  87131. }
  87132. /**
  87133. * Gets camera class name
  87134. * @returns StereoscopicFreeCamera
  87135. */
  87136. StereoscopicFreeCamera.prototype.getClassName = function () {
  87137. return "StereoscopicFreeCamera";
  87138. };
  87139. return StereoscopicFreeCamera;
  87140. }(BABYLON.FreeCamera));
  87141. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87142. /**
  87143. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87144. */
  87145. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87146. __extends(StereoscopicArcRotateCamera, _super);
  87147. /**
  87148. * Creates a new StereoscopicArcRotateCamera
  87149. * @param name defines camera name
  87150. * @param alpha defines alpha angle (in radians)
  87151. * @param beta defines beta angle (in radians)
  87152. * @param radius defines radius
  87153. * @param target defines camera target
  87154. * @param interaxialDistance defines distance between each color axis
  87155. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87156. * @param scene defines the hosting scene
  87157. */
  87158. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87159. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87160. _this.interaxialDistance = interaxialDistance;
  87161. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87162. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87163. return _this;
  87164. }
  87165. /**
  87166. * Gets camera class name
  87167. * @returns StereoscopicArcRotateCamera
  87168. */
  87169. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87170. return "StereoscopicArcRotateCamera";
  87171. };
  87172. return StereoscopicArcRotateCamera;
  87173. }(BABYLON.ArcRotateCamera));
  87174. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87175. /**
  87176. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87177. */
  87178. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87179. __extends(StereoscopicGamepadCamera, _super);
  87180. /**
  87181. * Creates a new StereoscopicGamepadCamera
  87182. * @param name defines camera name
  87183. * @param position defines initial position
  87184. * @param interaxialDistance defines distance between each color axis
  87185. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87186. * @param scene defines the hosting scene
  87187. */
  87188. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87189. var _this = _super.call(this, name, position, scene) || this;
  87190. _this.interaxialDistance = interaxialDistance;
  87191. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87192. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87193. return _this;
  87194. }
  87195. /**
  87196. * Gets camera class name
  87197. * @returns StereoscopicGamepadCamera
  87198. */
  87199. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87200. return "StereoscopicGamepadCamera";
  87201. };
  87202. return StereoscopicGamepadCamera;
  87203. }(BABYLON.GamepadCamera));
  87204. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87205. /**
  87206. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87207. */
  87208. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87209. __extends(StereoscopicUniversalCamera, _super);
  87210. /**
  87211. * Creates a new StereoscopicUniversalCamera
  87212. * @param name defines camera name
  87213. * @param position defines initial position
  87214. * @param interaxialDistance defines distance between each color axis
  87215. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87216. * @param scene defines the hosting scene
  87217. */
  87218. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87219. var _this = _super.call(this, name, position, scene) || this;
  87220. _this.interaxialDistance = interaxialDistance;
  87221. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87222. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87223. return _this;
  87224. }
  87225. /**
  87226. * Gets camera class name
  87227. * @returns StereoscopicUniversalCamera
  87228. */
  87229. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87230. return "StereoscopicUniversalCamera";
  87231. };
  87232. return StereoscopicUniversalCamera;
  87233. }(BABYLON.UniversalCamera));
  87234. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87235. })(BABYLON || (BABYLON = {}));
  87236. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87237. var BABYLON;
  87238. (function (BABYLON) {
  87239. var VRExperienceHelperGazer = /** @class */ (function () {
  87240. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87241. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87242. this.scene = scene;
  87243. this._pointerDownOnMeshAsked = false;
  87244. this._isActionableMesh = false;
  87245. this._teleportationRequestInitiated = false;
  87246. this._teleportationBackRequestInitiated = false;
  87247. this._dpadPressed = true;
  87248. this._activePointer = false;
  87249. this._id = VRExperienceHelperGazer._idCounter++;
  87250. // Gaze tracker
  87251. if (!gazeTrackerToClone) {
  87252. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87253. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87254. this._gazeTracker.isPickable = false;
  87255. this._gazeTracker.isVisible = false;
  87256. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87257. targetMat.specularColor = BABYLON.Color3.Black();
  87258. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87259. targetMat.backFaceCulling = false;
  87260. this._gazeTracker.material = targetMat;
  87261. }
  87262. else {
  87263. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87264. }
  87265. }
  87266. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87267. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87268. };
  87269. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87270. this._pointerDownOnMeshAsked = true;
  87271. if (this._currentMeshSelected && this._currentHit) {
  87272. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87273. }
  87274. };
  87275. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87276. if (this._currentMeshSelected && this._currentHit) {
  87277. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87278. }
  87279. this._pointerDownOnMeshAsked = false;
  87280. };
  87281. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87282. this._activePointer = true;
  87283. };
  87284. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87285. this._activePointer = false;
  87286. };
  87287. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87288. };
  87289. VRExperienceHelperGazer.prototype.dispose = function () {
  87290. this._interactionsEnabled = false;
  87291. this._teleportationEnabled = false;
  87292. };
  87293. VRExperienceHelperGazer._idCounter = 0;
  87294. return VRExperienceHelperGazer;
  87295. }());
  87296. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87297. __extends(VRExperienceHelperControllerGazer, _super);
  87298. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87299. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87300. _this.webVRController = webVRController;
  87301. // Laser pointer
  87302. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87303. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87304. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87305. laserPointerMaterial.alpha = 0.6;
  87306. _this._laserPointer.material = laserPointerMaterial;
  87307. _this._laserPointer.rotation.x = Math.PI / 2;
  87308. _this._laserPointer.position.z = -0.5;
  87309. _this._laserPointer.isVisible = false;
  87310. if (!webVRController.mesh) {
  87311. // Create an empty mesh that is used prior to loading the high quality model
  87312. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87313. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87314. preloadPointerPose.rotation.x = -0.7;
  87315. preloadMesh.addChild(preloadPointerPose);
  87316. webVRController.attachToMesh(preloadMesh);
  87317. }
  87318. _this._setLaserPointerParent(webVRController.mesh);
  87319. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87320. _this._setLaserPointerParent(mesh);
  87321. });
  87322. return _this;
  87323. }
  87324. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87325. return this.webVRController.getForwardRay(length);
  87326. };
  87327. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87328. _super.prototype._activatePointer.call(this);
  87329. this._laserPointer.isVisible = true;
  87330. };
  87331. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87332. _super.prototype._deactivatePointer.call(this);
  87333. this._laserPointer.isVisible = false;
  87334. };
  87335. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87336. this._laserPointer.material.emissiveColor = color;
  87337. };
  87338. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87339. var makeNotPick = function (root) {
  87340. root.name += " laserPointer";
  87341. root.getChildMeshes().forEach(function (c) {
  87342. makeNotPick(c);
  87343. });
  87344. };
  87345. makeNotPick(mesh);
  87346. var childMeshes = mesh.getChildMeshes();
  87347. this.webVRController._pointingPoseNode = null;
  87348. for (var i = 0; i < childMeshes.length; i++) {
  87349. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87350. mesh = childMeshes[i];
  87351. this.webVRController._pointingPoseNode = mesh;
  87352. break;
  87353. }
  87354. }
  87355. this._laserPointer.parent = mesh;
  87356. };
  87357. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87358. this._laserPointer.scaling.y = distance;
  87359. this._laserPointer.position.z = -distance / 2;
  87360. };
  87361. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87362. _super.prototype.dispose.call(this);
  87363. this._laserPointer.dispose();
  87364. if (this._meshAttachedObserver) {
  87365. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87366. }
  87367. };
  87368. return VRExperienceHelperControllerGazer;
  87369. }(VRExperienceHelperGazer));
  87370. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87371. __extends(VRExperienceHelperCameraGazer, _super);
  87372. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87373. var _this = _super.call(this, scene) || this;
  87374. _this.getCamera = getCamera;
  87375. return _this;
  87376. }
  87377. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87378. var camera = this.getCamera();
  87379. if (camera) {
  87380. return camera.getForwardRay(length);
  87381. }
  87382. else {
  87383. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87384. }
  87385. };
  87386. return VRExperienceHelperCameraGazer;
  87387. }(VRExperienceHelperGazer));
  87388. /**
  87389. * Helps to quickly add VR support to an existing scene.
  87390. * See http://doc.babylonjs.com/how_to/webvr_helper
  87391. */
  87392. var VRExperienceHelper = /** @class */ (function () {
  87393. /**
  87394. * Instantiates a VRExperienceHelper.
  87395. * Helps to quickly add VR support to an existing scene.
  87396. * @param scene The scene the VRExperienceHelper belongs to.
  87397. * @param webVROptions Options to modify the vr experience helper's behavior.
  87398. */
  87399. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87400. if (webVROptions === void 0) { webVROptions = {}; }
  87401. var _this = this;
  87402. this.webVROptions = webVROptions;
  87403. // Can the system support WebVR, even if a headset isn't plugged in?
  87404. this._webVRsupported = false;
  87405. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87406. this._webVRready = false;
  87407. // Are we waiting for the requestPresent callback to complete?
  87408. this._webVRrequesting = false;
  87409. // Are we presenting to the headset right now?
  87410. this._webVRpresenting = false;
  87411. // Are we presenting in the fullscreen fallback?
  87412. this._fullscreenVRpresenting = false;
  87413. /**
  87414. * Observable raised when entering VR.
  87415. */
  87416. this.onEnteringVRObservable = new BABYLON.Observable();
  87417. /**
  87418. * Observable raised when exiting VR.
  87419. */
  87420. this.onExitingVRObservable = new BABYLON.Observable();
  87421. /**
  87422. * Observable raised when controller mesh is loaded.
  87423. */
  87424. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87425. this._useCustomVRButton = false;
  87426. this._teleportationRequested = false;
  87427. this._teleportActive = false;
  87428. this._floorMeshesCollection = [];
  87429. this._rotationAllowed = true;
  87430. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87431. this._rotationRightAsked = false;
  87432. this._rotationLeftAsked = false;
  87433. this._isDefaultTeleportationTarget = true;
  87434. this._teleportationFillColor = "#444444";
  87435. this._teleportationBorderColor = "#FFFFFF";
  87436. this._rotationAngle = 0;
  87437. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87438. this._padSensibilityUp = 0.65;
  87439. this._padSensibilityDown = 0.35;
  87440. this.leftController = null;
  87441. this.rightController = null;
  87442. /**
  87443. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87444. */
  87445. this.onNewMeshSelected = new BABYLON.Observable();
  87446. /**
  87447. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87448. */
  87449. this.onNewMeshPicked = new BABYLON.Observable();
  87450. /**
  87451. * Observable raised before camera teleportation
  87452. */
  87453. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87454. /**
  87455. * Observable raised after camera teleportation
  87456. */
  87457. this.onAfterCameraTeleport = new BABYLON.Observable();
  87458. /**
  87459. * Observable raised when current selected mesh gets unselected
  87460. */
  87461. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87462. /**
  87463. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87464. */
  87465. this.teleportationEnabled = true;
  87466. this._teleportationInitialized = false;
  87467. this._interactionsEnabled = false;
  87468. this._interactionsRequested = false;
  87469. this._displayGaze = true;
  87470. this._displayLaserPointer = true;
  87471. this._onResize = function () {
  87472. _this.moveButtonToBottomRight();
  87473. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87474. _this.exitVR();
  87475. }
  87476. };
  87477. this._onFullscreenChange = function () {
  87478. if (document.fullscreen !== undefined) {
  87479. _this._fullscreenVRpresenting = document.fullscreen;
  87480. }
  87481. else if (document.mozFullScreen !== undefined) {
  87482. _this._fullscreenVRpresenting = document.mozFullScreen;
  87483. }
  87484. else if (document.webkitIsFullScreen !== undefined) {
  87485. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87486. }
  87487. else if (document.msIsFullScreen !== undefined) {
  87488. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87489. }
  87490. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87491. _this.exitVR();
  87492. if (!_this._useCustomVRButton) {
  87493. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87494. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87495. }
  87496. }
  87497. };
  87498. this.beforeRender = function () {
  87499. if (_this.leftController && _this.leftController._activePointer) {
  87500. _this._castRayAndSelectObject(_this.leftController);
  87501. }
  87502. if (_this.rightController && _this.rightController._activePointer) {
  87503. _this._castRayAndSelectObject(_this.rightController);
  87504. }
  87505. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87506. _this._castRayAndSelectObject(_this._cameraGazer);
  87507. }
  87508. else {
  87509. _this._cameraGazer._gazeTracker.isVisible = false;
  87510. }
  87511. };
  87512. this._onNewGamepadConnected = function (gamepad) {
  87513. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87514. if (gamepad.leftStick) {
  87515. gamepad.onleftstickchanged(function (stickValues) {
  87516. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87517. // Listening to classic/xbox gamepad only if no VR controller is active
  87518. if ((!_this.leftController && !_this.rightController) ||
  87519. ((_this.leftController && !_this.leftController._activePointer) &&
  87520. (_this.rightController && !_this.rightController._activePointer))) {
  87521. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87522. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87523. }
  87524. }
  87525. });
  87526. }
  87527. if (gamepad.rightStick) {
  87528. gamepad.onrightstickchanged(function (stickValues) {
  87529. if (_this._teleportationInitialized) {
  87530. _this._checkRotate(stickValues, _this._cameraGazer);
  87531. }
  87532. });
  87533. }
  87534. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87535. gamepad.onbuttondown(function (buttonPressed) {
  87536. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87537. _this._cameraGazer._selectionPointerDown();
  87538. }
  87539. });
  87540. gamepad.onbuttonup(function (buttonPressed) {
  87541. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87542. _this._cameraGazer._selectionPointerUp();
  87543. }
  87544. });
  87545. }
  87546. }
  87547. else {
  87548. var webVRController = gamepad;
  87549. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87550. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87551. _this.rightController = controller;
  87552. }
  87553. else {
  87554. _this.leftController = controller;
  87555. }
  87556. _this._tryEnableInteractionOnController(controller);
  87557. }
  87558. };
  87559. // 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
  87560. this._tryEnableInteractionOnController = function (controller) {
  87561. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87562. _this._enableInteractionOnController(controller);
  87563. }
  87564. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87565. _this._enableTeleportationOnController(controller);
  87566. }
  87567. };
  87568. this._onNewGamepadDisconnected = function (gamepad) {
  87569. if (gamepad instanceof BABYLON.WebVRController) {
  87570. if (gamepad.hand === "left" && _this.leftController != null) {
  87571. _this.leftController.dispose();
  87572. _this.leftController = null;
  87573. }
  87574. if (gamepad.hand === "right" && _this.rightController != null) {
  87575. _this.rightController.dispose();
  87576. _this.rightController = null;
  87577. }
  87578. }
  87579. };
  87580. this._workingVector = BABYLON.Vector3.Zero();
  87581. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87582. this._workingMatrix = BABYLON.Matrix.Identity();
  87583. this._scene = scene;
  87584. this._canvas = scene.getEngine().getRenderingCanvas();
  87585. // Parse options
  87586. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87587. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87588. }
  87589. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87590. webVROptions.createDeviceOrientationCamera = true;
  87591. }
  87592. if (webVROptions.defaultHeight === undefined) {
  87593. webVROptions.defaultHeight = 1.7;
  87594. }
  87595. if (webVROptions.useCustomVRButton) {
  87596. this._useCustomVRButton = true;
  87597. if (webVROptions.customVRButton) {
  87598. this._btnVR = webVROptions.customVRButton;
  87599. }
  87600. }
  87601. if (webVROptions.rayLength) {
  87602. this._rayLength = webVROptions.rayLength;
  87603. }
  87604. this._defaultHeight = webVROptions.defaultHeight;
  87605. if (webVROptions.positionScale) {
  87606. this._rayLength *= webVROptions.positionScale;
  87607. this._defaultHeight *= webVROptions.positionScale;
  87608. }
  87609. // Set position
  87610. if (this._scene.activeCamera) {
  87611. this._position = this._scene.activeCamera.position.clone();
  87612. }
  87613. else {
  87614. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87615. }
  87616. // Set non-vr camera
  87617. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87618. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87619. // Copy data from existing camera
  87620. if (this._scene.activeCamera) {
  87621. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87622. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87623. // Set rotation from previous camera
  87624. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87625. var targetCamera = this._scene.activeCamera;
  87626. if (targetCamera.rotationQuaternion) {
  87627. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87628. }
  87629. else {
  87630. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87631. }
  87632. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87633. }
  87634. }
  87635. this._scene.activeCamera = this._deviceOrientationCamera;
  87636. if (this._canvas) {
  87637. this._scene.activeCamera.attachControl(this._canvas);
  87638. }
  87639. }
  87640. else {
  87641. this._existingCamera = this._scene.activeCamera;
  87642. }
  87643. // Create VR cameras
  87644. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87645. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87646. }
  87647. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87648. this._webVRCamera.useStandingMatrix();
  87649. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87650. // Create default button
  87651. if (!this._useCustomVRButton) {
  87652. this._btnVR = document.createElement("BUTTON");
  87653. this._btnVR.className = "babylonVRicon";
  87654. this._btnVR.id = "babylonVRiconbtn";
  87655. this._btnVR.title = "Click to switch to VR";
  87656. 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) }";
  87657. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87658. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87659. // css += ".babylonVRicon.vrdisplaysupported { }";
  87660. // css += ".babylonVRicon.vrdisplayready { }";
  87661. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87662. var style = document.createElement('style');
  87663. style.appendChild(document.createTextNode(css));
  87664. document.getElementsByTagName('head')[0].appendChild(style);
  87665. this.moveButtonToBottomRight();
  87666. }
  87667. // VR button click event
  87668. if (this._btnVR) {
  87669. this._btnVR.addEventListener("click", function () {
  87670. if (!_this.isInVRMode) {
  87671. _this.enterVR();
  87672. }
  87673. else {
  87674. _this.exitVR();
  87675. }
  87676. });
  87677. }
  87678. // Window events
  87679. window.addEventListener("resize", this._onResize);
  87680. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87681. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87682. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87683. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87684. // Display vr button when headset is connected
  87685. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87686. this.displayVRButton();
  87687. }
  87688. else {
  87689. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87690. if (e.vrDisplay) {
  87691. _this.displayVRButton();
  87692. }
  87693. });
  87694. }
  87695. // Exiting VR mode using 'ESC' key on desktop
  87696. this._onKeyDown = function (event) {
  87697. if (event.keyCode === 27 && _this.isInVRMode) {
  87698. _this.exitVR();
  87699. }
  87700. };
  87701. document.addEventListener("keydown", this._onKeyDown);
  87702. // Exiting VR mode double tapping the touch screen
  87703. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87704. if (_this.isInVRMode) {
  87705. _this.exitVR();
  87706. if (_this._fullscreenVRpresenting) {
  87707. _this._scene.getEngine().switchFullscreen(true);
  87708. }
  87709. }
  87710. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87711. // Listen for WebVR display changes
  87712. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87713. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87714. this._onVRRequestPresentStart = function () {
  87715. _this._webVRrequesting = true;
  87716. _this.updateButtonVisibility();
  87717. };
  87718. this._onVRRequestPresentComplete = function (success) {
  87719. _this._webVRrequesting = false;
  87720. _this.updateButtonVisibility();
  87721. };
  87722. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87723. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87724. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87725. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87726. scene.onDisposeObservable.add(function () {
  87727. _this.dispose();
  87728. });
  87729. // Gamepad connection events
  87730. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87731. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87732. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87733. this.updateButtonVisibility();
  87734. //create easing functions
  87735. this._circleEase = new BABYLON.CircleEase();
  87736. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87737. }
  87738. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87739. /** Return this.onEnteringVRObservable
  87740. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87741. */
  87742. get: function () {
  87743. return this.onEnteringVRObservable;
  87744. },
  87745. enumerable: true,
  87746. configurable: true
  87747. });
  87748. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87749. /** Return this.onExitingVRObservable
  87750. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87751. */
  87752. get: function () {
  87753. return this.onExitingVRObservable;
  87754. },
  87755. enumerable: true,
  87756. configurable: true
  87757. });
  87758. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87759. /** Return this.onControllerMeshLoadedObservable
  87760. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87761. */
  87762. get: function () {
  87763. return this.onControllerMeshLoadedObservable;
  87764. },
  87765. enumerable: true,
  87766. configurable: true
  87767. });
  87768. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87769. /**
  87770. * The mesh used to display where the user is going to teleport.
  87771. */
  87772. get: function () {
  87773. return this._teleportationTarget;
  87774. },
  87775. /**
  87776. * Sets the mesh to be used to display where the user is going to teleport.
  87777. */
  87778. set: function (value) {
  87779. if (value) {
  87780. value.name = "teleportationTarget";
  87781. this._isDefaultTeleportationTarget = false;
  87782. this._teleportationTarget = value;
  87783. }
  87784. },
  87785. enumerable: true,
  87786. configurable: true
  87787. });
  87788. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87789. /**
  87790. * The mesh used to display where the user is selecting,
  87791. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87792. * See http://doc.babylonjs.com/resources/baking_transformations
  87793. */
  87794. get: function () {
  87795. return this._cameraGazer._gazeTracker;
  87796. },
  87797. set: function (value) {
  87798. if (value) {
  87799. this._cameraGazer._gazeTracker = value;
  87800. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87801. this._cameraGazer._gazeTracker.isPickable = false;
  87802. this._cameraGazer._gazeTracker.isVisible = false;
  87803. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87804. if (this.leftController) {
  87805. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87806. }
  87807. if (this.rightController) {
  87808. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87809. }
  87810. }
  87811. },
  87812. enumerable: true,
  87813. configurable: true
  87814. });
  87815. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87816. /**
  87817. * If the ray of the gaze should be displayed.
  87818. */
  87819. get: function () {
  87820. return this._displayGaze;
  87821. },
  87822. /**
  87823. * Sets if the ray of the gaze should be displayed.
  87824. */
  87825. set: function (value) {
  87826. this._displayGaze = value;
  87827. if (!value) {
  87828. this._cameraGazer._gazeTracker.isVisible = false;
  87829. if (this.leftController) {
  87830. this.leftController._gazeTracker.isVisible = false;
  87831. }
  87832. if (this.rightController) {
  87833. this.rightController._gazeTracker.isVisible = false;
  87834. }
  87835. }
  87836. },
  87837. enumerable: true,
  87838. configurable: true
  87839. });
  87840. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87841. /**
  87842. * If the ray of the LaserPointer should be displayed.
  87843. */
  87844. get: function () {
  87845. return this._displayLaserPointer;
  87846. },
  87847. /**
  87848. * Sets if the ray of the LaserPointer should be displayed.
  87849. */
  87850. set: function (value) {
  87851. this._displayLaserPointer = value;
  87852. if (!value) {
  87853. if (this.rightController) {
  87854. this.rightController._deactivatePointer();
  87855. this.rightController._gazeTracker.isVisible = false;
  87856. }
  87857. if (this.leftController) {
  87858. this.leftController._deactivatePointer();
  87859. this.leftController._gazeTracker.isVisible = false;
  87860. }
  87861. }
  87862. else {
  87863. if (this.rightController) {
  87864. this.rightController._activatePointer();
  87865. }
  87866. else if (this.leftController) {
  87867. this.leftController._activatePointer();
  87868. }
  87869. }
  87870. },
  87871. enumerable: true,
  87872. configurable: true
  87873. });
  87874. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87875. /**
  87876. * The deviceOrientationCamera used as the camera when not in VR.
  87877. */
  87878. get: function () {
  87879. return this._deviceOrientationCamera;
  87880. },
  87881. enumerable: true,
  87882. configurable: true
  87883. });
  87884. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87885. /**
  87886. * Based on the current WebVR support, returns the current VR camera used.
  87887. */
  87888. get: function () {
  87889. if (this._webVRready) {
  87890. return this._webVRCamera;
  87891. }
  87892. else {
  87893. return this._scene.activeCamera;
  87894. }
  87895. },
  87896. enumerable: true,
  87897. configurable: true
  87898. });
  87899. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87900. /**
  87901. * The webVRCamera which is used when in VR.
  87902. */
  87903. get: function () {
  87904. return this._webVRCamera;
  87905. },
  87906. enumerable: true,
  87907. configurable: true
  87908. });
  87909. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87910. /**
  87911. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87912. */
  87913. get: function () {
  87914. return this._vrDeviceOrientationCamera;
  87915. },
  87916. enumerable: true,
  87917. configurable: true
  87918. });
  87919. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87920. get: function () {
  87921. var result = this._cameraGazer._teleportationRequestInitiated
  87922. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87923. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87924. return result;
  87925. },
  87926. enumerable: true,
  87927. configurable: true
  87928. });
  87929. // Raised when one of the controller has loaded successfully its associated default mesh
  87930. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87931. if (this.leftController && this.leftController.webVRController == webVRController) {
  87932. if (webVRController.mesh) {
  87933. this.leftController._setLaserPointerParent(webVRController.mesh);
  87934. }
  87935. }
  87936. if (this.rightController && this.rightController.webVRController == webVRController) {
  87937. if (webVRController.mesh) {
  87938. this.rightController._setLaserPointerParent(webVRController.mesh);
  87939. }
  87940. }
  87941. try {
  87942. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  87943. }
  87944. catch (err) {
  87945. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  87946. }
  87947. };
  87948. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  87949. /**
  87950. * Gets a value indicating if we are currently in VR mode.
  87951. */
  87952. get: function () {
  87953. return this._webVRpresenting || this._fullscreenVRpresenting;
  87954. },
  87955. enumerable: true,
  87956. configurable: true
  87957. });
  87958. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  87959. var vrDisplay = this._scene.getEngine().getVRDevice();
  87960. if (vrDisplay) {
  87961. var wasPresenting = this._webVRpresenting;
  87962. // A VR display is connected
  87963. this._webVRpresenting = vrDisplay.isPresenting;
  87964. if (wasPresenting && !this._webVRpresenting)
  87965. this.exitVR();
  87966. }
  87967. else {
  87968. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  87969. }
  87970. this.updateButtonVisibility();
  87971. };
  87972. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  87973. this._webVRsupported = eventArgs.vrSupported;
  87974. this._webVRready = !!eventArgs.vrDisplay;
  87975. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  87976. this.updateButtonVisibility();
  87977. };
  87978. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  87979. if (this._canvas && !this._useCustomVRButton) {
  87980. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  87981. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  87982. }
  87983. };
  87984. VRExperienceHelper.prototype.displayVRButton = function () {
  87985. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  87986. document.body.appendChild(this._btnVR);
  87987. this._btnVRDisplayed = true;
  87988. }
  87989. };
  87990. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  87991. if (!this._btnVR || this._useCustomVRButton) {
  87992. return;
  87993. }
  87994. this._btnVR.className = "babylonVRicon";
  87995. if (this.isInVRMode) {
  87996. this._btnVR.className += " vrdisplaypresenting";
  87997. }
  87998. else {
  87999. if (this._webVRready)
  88000. this._btnVR.className += " vrdisplayready";
  88001. if (this._webVRsupported)
  88002. this._btnVR.className += " vrdisplaysupported";
  88003. if (this._webVRrequesting)
  88004. this._btnVR.className += " vrdisplayrequesting";
  88005. }
  88006. };
  88007. /**
  88008. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88009. * Otherwise, will use the fullscreen API.
  88010. */
  88011. VRExperienceHelper.prototype.enterVR = function () {
  88012. if (this.onEnteringVRObservable) {
  88013. try {
  88014. this.onEnteringVRObservable.notifyObservers(this);
  88015. }
  88016. catch (err) {
  88017. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88018. }
  88019. }
  88020. if (this._scene.activeCamera) {
  88021. this._position = this._scene.activeCamera.position.clone();
  88022. // make sure that we return to the last active camera
  88023. this._existingCamera = this._scene.activeCamera;
  88024. }
  88025. if (this._webVRrequesting)
  88026. return;
  88027. // If WebVR is supported and a headset is connected
  88028. if (this._webVRready) {
  88029. if (!this._webVRpresenting) {
  88030. this._webVRCamera.position = this._position;
  88031. this._scene.activeCamera = this._webVRCamera;
  88032. }
  88033. }
  88034. else if (this._vrDeviceOrientationCamera) {
  88035. this._vrDeviceOrientationCamera.position = this._position;
  88036. if (this._scene.activeCamera) {
  88037. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88038. }
  88039. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88040. this._scene.getEngine().switchFullscreen(true);
  88041. this.updateButtonVisibility();
  88042. }
  88043. if (this._scene.activeCamera && this._canvas) {
  88044. this._scene.activeCamera.attachControl(this._canvas);
  88045. }
  88046. if (this._interactionsEnabled) {
  88047. this._scene.registerBeforeRender(this.beforeRender);
  88048. }
  88049. };
  88050. /**
  88051. * Attempt to exit VR, or fullscreen.
  88052. */
  88053. VRExperienceHelper.prototype.exitVR = function () {
  88054. if (this.onExitingVRObservable) {
  88055. try {
  88056. this.onExitingVRObservable.notifyObservers(this);
  88057. }
  88058. catch (err) {
  88059. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88060. }
  88061. }
  88062. if (this._webVRpresenting) {
  88063. this._scene.getEngine().disableVR();
  88064. }
  88065. if (this._scene.activeCamera) {
  88066. this._position = this._scene.activeCamera.position.clone();
  88067. }
  88068. if (this._deviceOrientationCamera) {
  88069. this._deviceOrientationCamera.position = this._position;
  88070. this._scene.activeCamera = this._deviceOrientationCamera;
  88071. if (this._canvas) {
  88072. this._scene.activeCamera.attachControl(this._canvas);
  88073. }
  88074. }
  88075. else if (this._existingCamera) {
  88076. this._existingCamera.position = this._position;
  88077. this._scene.activeCamera = this._existingCamera;
  88078. }
  88079. this.updateButtonVisibility();
  88080. if (this._interactionsEnabled) {
  88081. this._scene.unregisterBeforeRender(this.beforeRender);
  88082. }
  88083. // resize to update width and height when exiting vr exits fullscreen
  88084. this._scene.getEngine().resize();
  88085. };
  88086. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88087. /**
  88088. * The position of the vr experience helper.
  88089. */
  88090. get: function () {
  88091. return this._position;
  88092. },
  88093. /**
  88094. * Sets the position of the vr experience helper.
  88095. */
  88096. set: function (value) {
  88097. this._position = value;
  88098. if (this._scene.activeCamera) {
  88099. this._scene.activeCamera.position = value;
  88100. }
  88101. },
  88102. enumerable: true,
  88103. configurable: true
  88104. });
  88105. /**
  88106. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88107. */
  88108. VRExperienceHelper.prototype.enableInteractions = function () {
  88109. var _this = this;
  88110. if (!this._interactionsEnabled) {
  88111. this._interactionsRequested = true;
  88112. if (this.leftController) {
  88113. this._enableInteractionOnController(this.leftController);
  88114. }
  88115. if (this.rightController) {
  88116. this._enableInteractionOnController(this.rightController);
  88117. }
  88118. this.raySelectionPredicate = function (mesh) {
  88119. return mesh.isVisible;
  88120. };
  88121. this.meshSelectionPredicate = function (mesh) {
  88122. return true;
  88123. };
  88124. this._raySelectionPredicate = function (mesh) {
  88125. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88126. && mesh.name.indexOf("teleportationTarget") === -1
  88127. && mesh.name.indexOf("torusTeleportation") === -1
  88128. && mesh.name.indexOf("laserPointer") === -1)) {
  88129. return _this.raySelectionPredicate(mesh);
  88130. }
  88131. return false;
  88132. };
  88133. this._interactionsEnabled = true;
  88134. }
  88135. };
  88136. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88137. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88138. if (this._floorMeshesCollection[i].id === mesh.id) {
  88139. return true;
  88140. }
  88141. }
  88142. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88143. return true;
  88144. }
  88145. return false;
  88146. };
  88147. /**
  88148. * Adds a floor mesh to be used for teleportation.
  88149. * @param floorMesh the mesh to be used for teleportation.
  88150. */
  88151. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88152. if (!this._floorMeshesCollection) {
  88153. return;
  88154. }
  88155. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88156. return;
  88157. }
  88158. this._floorMeshesCollection.push(floorMesh);
  88159. };
  88160. /**
  88161. * Removes a floor mesh from being used for teleportation.
  88162. * @param floorMesh the mesh to be removed.
  88163. */
  88164. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88165. if (!this._floorMeshesCollection) {
  88166. return;
  88167. }
  88168. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88169. if (meshIndex !== -1) {
  88170. this._floorMeshesCollection.splice(meshIndex, 1);
  88171. }
  88172. };
  88173. /**
  88174. * Enables interactions and teleportation using the VR controllers and gaze.
  88175. * @param vrTeleportationOptions options to modify teleportation behavior.
  88176. */
  88177. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88178. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88179. if (!this._teleportationInitialized) {
  88180. this._teleportationRequested = true;
  88181. this.enableInteractions();
  88182. if (vrTeleportationOptions.floorMeshName) {
  88183. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88184. }
  88185. if (vrTeleportationOptions.floorMeshes) {
  88186. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88187. }
  88188. if (this.leftController != null) {
  88189. this._enableTeleportationOnController(this.leftController);
  88190. }
  88191. if (this.rightController != null) {
  88192. this._enableTeleportationOnController(this.rightController);
  88193. }
  88194. // Creates an image processing post process for the vignette not relying
  88195. // on the main scene configuration for image processing to reduce setup and spaces
  88196. // (gamma/linear) conflicts.
  88197. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88198. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88199. imageProcessingConfiguration.vignetteEnabled = true;
  88200. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88201. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88202. this._teleportationInitialized = true;
  88203. if (this._isDefaultTeleportationTarget) {
  88204. this._createTeleportationCircles();
  88205. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88206. }
  88207. }
  88208. };
  88209. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88210. var _this = this;
  88211. var controllerMesh = controller.webVRController.mesh;
  88212. if (controllerMesh) {
  88213. controller._interactionsEnabled = true;
  88214. controller._activatePointer();
  88215. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88216. // Enabling / disabling laserPointer
  88217. if (_this._displayLaserPointer && stateObject.value === 1) {
  88218. if (controller._activePointer) {
  88219. controller._deactivatePointer();
  88220. }
  88221. else {
  88222. controller._activatePointer();
  88223. }
  88224. if (_this.displayGaze) {
  88225. controller._gazeTracker.isVisible = controller._activePointer;
  88226. }
  88227. }
  88228. });
  88229. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88230. if (!controller._pointerDownOnMeshAsked) {
  88231. if (stateObject.value > _this._padSensibilityUp) {
  88232. controller._selectionPointerDown();
  88233. }
  88234. }
  88235. else if (stateObject.value < _this._padSensibilityDown) {
  88236. controller._selectionPointerUp();
  88237. }
  88238. });
  88239. }
  88240. };
  88241. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88242. // Dont teleport if another gaze already requested teleportation
  88243. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88244. return;
  88245. }
  88246. if (!gazer._teleportationRequestInitiated) {
  88247. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88248. gazer._activatePointer();
  88249. gazer._teleportationRequestInitiated = true;
  88250. }
  88251. }
  88252. else {
  88253. // Listening to the proper controller values changes to confirm teleportation
  88254. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88255. if (this._teleportActive) {
  88256. this._teleportCamera(this._haloCenter);
  88257. }
  88258. gazer._teleportationRequestInitiated = false;
  88259. }
  88260. }
  88261. };
  88262. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88263. // Only rotate when user is not currently selecting a teleportation location
  88264. if (gazer._teleportationRequestInitiated) {
  88265. return;
  88266. }
  88267. if (!this._rotationLeftAsked) {
  88268. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88269. this._rotationLeftAsked = true;
  88270. if (this._rotationAllowed) {
  88271. this._rotateCamera(false);
  88272. }
  88273. }
  88274. }
  88275. else {
  88276. if (stateObject.x > -this._padSensibilityDown) {
  88277. this._rotationLeftAsked = false;
  88278. }
  88279. }
  88280. if (!this._rotationRightAsked) {
  88281. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88282. this._rotationRightAsked = true;
  88283. if (this._rotationAllowed) {
  88284. this._rotateCamera(true);
  88285. }
  88286. }
  88287. }
  88288. else {
  88289. if (stateObject.x < this._padSensibilityDown) {
  88290. this._rotationRightAsked = false;
  88291. }
  88292. }
  88293. };
  88294. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88295. // Only teleport backwards when user is not currently selecting a teleportation location
  88296. if (gazer._teleportationRequestInitiated) {
  88297. return;
  88298. }
  88299. // Teleport backwards
  88300. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88301. if (!gazer._teleportationBackRequestInitiated) {
  88302. if (!this.currentVRCamera) {
  88303. return;
  88304. }
  88305. // Get rotation and position of the current camera
  88306. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88307. var position = this.currentVRCamera.position;
  88308. // If the camera has device position, use that instead
  88309. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88310. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88311. position = this.currentVRCamera.devicePosition;
  88312. }
  88313. // Get matrix with only the y rotation of the device rotation
  88314. rotation.toEulerAnglesToRef(this._workingVector);
  88315. this._workingVector.z = 0;
  88316. this._workingVector.x = 0;
  88317. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88318. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88319. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88320. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88321. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88322. var ray = new BABYLON.Ray(position, this._workingVector);
  88323. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88324. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88325. this._teleportCamera(hit.pickedPoint);
  88326. }
  88327. gazer._teleportationBackRequestInitiated = true;
  88328. }
  88329. }
  88330. else {
  88331. gazer._teleportationBackRequestInitiated = false;
  88332. }
  88333. };
  88334. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88335. var _this = this;
  88336. var controllerMesh = controller.webVRController.mesh;
  88337. if (controllerMesh) {
  88338. if (!controller._interactionsEnabled) {
  88339. this._enableInteractionOnController(controller);
  88340. }
  88341. controller._interactionsEnabled = true;
  88342. controller._teleportationEnabled = true;
  88343. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88344. controller._dpadPressed = false;
  88345. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88346. controller._dpadPressed = stateObject.pressed;
  88347. if (!controller._dpadPressed) {
  88348. _this._rotationLeftAsked = false;
  88349. _this._rotationRightAsked = false;
  88350. controller._teleportationBackRequestInitiated = false;
  88351. }
  88352. });
  88353. }
  88354. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88355. if (_this.teleportationEnabled) {
  88356. _this._checkTeleportBackwards(stateObject, controller);
  88357. _this._checkTeleportWithRay(stateObject, controller);
  88358. }
  88359. _this._checkRotate(stateObject, controller);
  88360. });
  88361. }
  88362. };
  88363. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88364. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88365. this._teleportationTarget.isPickable = false;
  88366. var length = 512;
  88367. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88368. dynamicTexture.hasAlpha = true;
  88369. var context = dynamicTexture.getContext();
  88370. var centerX = length / 2;
  88371. var centerY = length / 2;
  88372. var radius = 200;
  88373. context.beginPath();
  88374. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88375. context.fillStyle = this._teleportationFillColor;
  88376. context.fill();
  88377. context.lineWidth = 10;
  88378. context.strokeStyle = this._teleportationBorderColor;
  88379. context.stroke();
  88380. context.closePath();
  88381. dynamicTexture.update();
  88382. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88383. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88384. this._teleportationTarget.material = teleportationCircleMaterial;
  88385. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88386. torus.isPickable = false;
  88387. torus.parent = this._teleportationTarget;
  88388. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88389. var keys = [];
  88390. keys.push({
  88391. frame: 0,
  88392. value: 0
  88393. });
  88394. keys.push({
  88395. frame: 30,
  88396. value: 0.4
  88397. });
  88398. keys.push({
  88399. frame: 60,
  88400. value: 0
  88401. });
  88402. animationInnerCircle.setKeys(keys);
  88403. var easingFunction = new BABYLON.SineEase();
  88404. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88405. animationInnerCircle.setEasingFunction(easingFunction);
  88406. torus.animations = [];
  88407. torus.animations.push(animationInnerCircle);
  88408. this._scene.beginAnimation(torus, 0, 60, true);
  88409. this._hideTeleportationTarget();
  88410. };
  88411. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88412. this._teleportActive = true;
  88413. if (this._teleportationInitialized) {
  88414. this._teleportationTarget.isVisible = true;
  88415. if (this._isDefaultTeleportationTarget) {
  88416. this._teleportationTarget.getChildren()[0].isVisible = true;
  88417. }
  88418. }
  88419. };
  88420. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88421. this._teleportActive = false;
  88422. if (this._teleportationInitialized) {
  88423. this._teleportationTarget.isVisible = false;
  88424. if (this._isDefaultTeleportationTarget) {
  88425. this._teleportationTarget.getChildren()[0].isVisible = false;
  88426. }
  88427. }
  88428. };
  88429. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88430. var _this = this;
  88431. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88432. return;
  88433. }
  88434. if (right) {
  88435. this._rotationAngle++;
  88436. }
  88437. else {
  88438. this._rotationAngle--;
  88439. }
  88440. this.currentVRCamera.animations = [];
  88441. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88442. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88443. var animationRotationKeys = [];
  88444. animationRotationKeys.push({
  88445. frame: 0,
  88446. value: this.currentVRCamera.rotationQuaternion
  88447. });
  88448. animationRotationKeys.push({
  88449. frame: 6,
  88450. value: target
  88451. });
  88452. animationRotation.setKeys(animationRotationKeys);
  88453. animationRotation.setEasingFunction(this._circleEase);
  88454. this.currentVRCamera.animations.push(animationRotation);
  88455. this._postProcessMove.animations = [];
  88456. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88457. var vignetteWeightKeys = [];
  88458. vignetteWeightKeys.push({
  88459. frame: 0,
  88460. value: 0
  88461. });
  88462. vignetteWeightKeys.push({
  88463. frame: 3,
  88464. value: 4
  88465. });
  88466. vignetteWeightKeys.push({
  88467. frame: 6,
  88468. value: 0
  88469. });
  88470. animationPP.setKeys(vignetteWeightKeys);
  88471. animationPP.setEasingFunction(this._circleEase);
  88472. this._postProcessMove.animations.push(animationPP);
  88473. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88474. var vignetteStretchKeys = [];
  88475. vignetteStretchKeys.push({
  88476. frame: 0,
  88477. value: 0
  88478. });
  88479. vignetteStretchKeys.push({
  88480. frame: 3,
  88481. value: 10
  88482. });
  88483. vignetteStretchKeys.push({
  88484. frame: 6,
  88485. value: 0
  88486. });
  88487. animationPP2.setKeys(vignetteStretchKeys);
  88488. animationPP2.setEasingFunction(this._circleEase);
  88489. this._postProcessMove.animations.push(animationPP2);
  88490. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88491. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88492. this._postProcessMove.samples = 4;
  88493. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88494. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88495. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88496. });
  88497. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88498. };
  88499. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88500. if (hit.pickedPoint) {
  88501. if (gazer._teleportationRequestInitiated) {
  88502. this._displayTeleportationTarget();
  88503. this._haloCenter.copyFrom(hit.pickedPoint);
  88504. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88505. }
  88506. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88507. if (pickNormal) {
  88508. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88509. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88510. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88511. }
  88512. this._teleportationTarget.position.y += 0.1;
  88513. }
  88514. };
  88515. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88516. var _this = this;
  88517. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88518. return;
  88519. }
  88520. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88521. // offset of the headset from the anchor.
  88522. if (this.webVRCamera.leftCamera) {
  88523. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88524. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88525. location.subtractToRef(this._workingVector, this._workingVector);
  88526. }
  88527. else {
  88528. this._workingVector.copyFrom(location);
  88529. }
  88530. // Add height to account for user's height offset
  88531. if (this.isInVRMode) {
  88532. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88533. }
  88534. else {
  88535. this._workingVector.y += this._defaultHeight;
  88536. }
  88537. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88538. // Create animation from the camera's position to the new location
  88539. this.currentVRCamera.animations = [];
  88540. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88541. var animationCameraTeleportationKeys = [{
  88542. frame: 0,
  88543. value: this.currentVRCamera.position
  88544. },
  88545. {
  88546. frame: 11,
  88547. value: this._workingVector
  88548. }
  88549. ];
  88550. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88551. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88552. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88553. this._postProcessMove.animations = [];
  88554. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88555. var vignetteWeightKeys = [];
  88556. vignetteWeightKeys.push({
  88557. frame: 0,
  88558. value: 0
  88559. });
  88560. vignetteWeightKeys.push({
  88561. frame: 5,
  88562. value: 8
  88563. });
  88564. vignetteWeightKeys.push({
  88565. frame: 11,
  88566. value: 0
  88567. });
  88568. animationPP.setKeys(vignetteWeightKeys);
  88569. this._postProcessMove.animations.push(animationPP);
  88570. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88571. var vignetteStretchKeys = [];
  88572. vignetteStretchKeys.push({
  88573. frame: 0,
  88574. value: 0
  88575. });
  88576. vignetteStretchKeys.push({
  88577. frame: 5,
  88578. value: 10
  88579. });
  88580. vignetteStretchKeys.push({
  88581. frame: 11,
  88582. value: 0
  88583. });
  88584. animationPP2.setKeys(vignetteStretchKeys);
  88585. this._postProcessMove.animations.push(animationPP2);
  88586. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88587. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88588. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88589. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88590. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88591. });
  88592. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88593. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88594. });
  88595. this._hideTeleportationTarget();
  88596. };
  88597. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88598. if (normal) {
  88599. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88600. if (angle < Math.PI / 2) {
  88601. normal.scaleInPlace(-1);
  88602. }
  88603. }
  88604. return normal;
  88605. };
  88606. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88607. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88608. return;
  88609. }
  88610. var ray = gazer._getForwardRay(this._rayLength);
  88611. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88612. // Moving the gazeTracker on the mesh face targetted
  88613. if (hit && hit.pickedPoint) {
  88614. if (this._displayGaze) {
  88615. var multiplier = 1;
  88616. gazer._gazeTracker.isVisible = true;
  88617. if (gazer._isActionableMesh) {
  88618. multiplier = 3;
  88619. }
  88620. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88621. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88622. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88623. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88624. // To avoid z-fighting
  88625. var deltaFighting = 0.002;
  88626. if (pickNormal) {
  88627. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88628. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88629. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88630. }
  88631. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88632. if (gazer._gazeTracker.position.x < 0) {
  88633. gazer._gazeTracker.position.x += deltaFighting;
  88634. }
  88635. else {
  88636. gazer._gazeTracker.position.x -= deltaFighting;
  88637. }
  88638. if (gazer._gazeTracker.position.y < 0) {
  88639. gazer._gazeTracker.position.y += deltaFighting;
  88640. }
  88641. else {
  88642. gazer._gazeTracker.position.y -= deltaFighting;
  88643. }
  88644. if (gazer._gazeTracker.position.z < 0) {
  88645. gazer._gazeTracker.position.z += deltaFighting;
  88646. }
  88647. else {
  88648. gazer._gazeTracker.position.z -= deltaFighting;
  88649. }
  88650. }
  88651. // Changing the size of the laser pointer based on the distance from the targetted point
  88652. gazer._updatePointerDistance(hit.distance);
  88653. }
  88654. else {
  88655. gazer._gazeTracker.isVisible = false;
  88656. }
  88657. if (hit && hit.pickedMesh) {
  88658. gazer._currentHit = hit;
  88659. if (gazer._pointerDownOnMeshAsked) {
  88660. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88661. }
  88662. // The object selected is the floor, we're in a teleportation scenario
  88663. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88664. // Moving the teleportation area to this targetted point
  88665. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88666. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88667. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88668. }
  88669. gazer._currentMeshSelected = null;
  88670. if (gazer._teleportationRequestInitiated) {
  88671. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88672. }
  88673. return;
  88674. }
  88675. // If not, we're in a selection scenario
  88676. //this._teleportationAllowed = false;
  88677. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88678. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88679. this.onNewMeshPicked.notifyObservers(hit);
  88680. gazer._currentMeshSelected = hit.pickedMesh;
  88681. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88682. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88683. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88684. gazer._isActionableMesh = true;
  88685. }
  88686. else {
  88687. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88688. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88689. gazer._isActionableMesh = false;
  88690. }
  88691. try {
  88692. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88693. }
  88694. catch (err) {
  88695. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88696. }
  88697. }
  88698. else {
  88699. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88700. gazer._currentMeshSelected = null;
  88701. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88702. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88703. }
  88704. }
  88705. }
  88706. else {
  88707. gazer._currentHit = null;
  88708. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88709. gazer._currentMeshSelected = null;
  88710. //this._teleportationAllowed = false;
  88711. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88712. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88713. }
  88714. };
  88715. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88716. if (mesh) {
  88717. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88718. }
  88719. };
  88720. /**
  88721. * Sets the color of the laser ray from the vr controllers.
  88722. * @param color new color for the ray.
  88723. */
  88724. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88725. if (this.leftController) {
  88726. this.leftController._setLaserPointerColor(color);
  88727. }
  88728. if (this.rightController) {
  88729. this.rightController._setLaserPointerColor(color);
  88730. }
  88731. };
  88732. /**
  88733. * Sets the color of the ray from the vr headsets gaze.
  88734. * @param color new color for the ray.
  88735. */
  88736. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88737. if (!this._cameraGazer._gazeTracker.material) {
  88738. return;
  88739. }
  88740. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88741. if (this.leftController) {
  88742. this.leftController._gazeTracker.material.emissiveColor = color;
  88743. }
  88744. if (this.rightController) {
  88745. this.rightController._gazeTracker.material.emissiveColor = color;
  88746. }
  88747. };
  88748. /**
  88749. * Exits VR and disposes of the vr experience helper
  88750. */
  88751. VRExperienceHelper.prototype.dispose = function () {
  88752. if (this.isInVRMode) {
  88753. this.exitVR();
  88754. }
  88755. if (this._postProcessMove) {
  88756. this._postProcessMove.dispose();
  88757. }
  88758. if (this._webVRCamera) {
  88759. this._webVRCamera.dispose();
  88760. }
  88761. if (this._vrDeviceOrientationCamera) {
  88762. this._vrDeviceOrientationCamera.dispose();
  88763. }
  88764. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88765. document.body.removeChild(this._btnVR);
  88766. }
  88767. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88768. this._deviceOrientationCamera.dispose();
  88769. }
  88770. if (this._cameraGazer) {
  88771. this._cameraGazer.dispose();
  88772. }
  88773. if (this.leftController) {
  88774. this.leftController.dispose();
  88775. }
  88776. if (this.rightController) {
  88777. this.rightController.dispose();
  88778. }
  88779. if (this._teleportationTarget) {
  88780. this._teleportationTarget.dispose();
  88781. }
  88782. this._floorMeshesCollection = [];
  88783. document.removeEventListener("keydown", this._onKeyDown);
  88784. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88785. window.removeEventListener("resize", this._onResize);
  88786. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88787. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88788. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88789. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88790. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88791. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88792. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88793. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88794. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88795. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88796. this._scene.unregisterBeforeRender(this.beforeRender);
  88797. };
  88798. /**
  88799. * Gets the name of the VRExperienceHelper class
  88800. * @returns "VRExperienceHelper"
  88801. */
  88802. VRExperienceHelper.prototype.getClassName = function () {
  88803. return "VRExperienceHelper";
  88804. };
  88805. return VRExperienceHelper;
  88806. }());
  88807. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88808. })(BABYLON || (BABYLON = {}));
  88809. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88810. // Mainly based on these 2 articles :
  88811. // 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
  88812. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88813. var BABYLON;
  88814. (function (BABYLON) {
  88815. /**
  88816. * Defines the potential axis of a Joystick
  88817. */
  88818. var JoystickAxis;
  88819. (function (JoystickAxis) {
  88820. /** X axis */
  88821. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88822. /** Y axis */
  88823. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88824. /** Z axis */
  88825. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88826. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88827. /**
  88828. * Class used to define virtual joystick (used in touch mode)
  88829. */
  88830. var VirtualJoystick = /** @class */ (function () {
  88831. /**
  88832. * Creates a new virtual joystick
  88833. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88834. */
  88835. function VirtualJoystick(leftJoystick) {
  88836. var _this = this;
  88837. if (leftJoystick) {
  88838. this._leftJoystick = true;
  88839. }
  88840. else {
  88841. this._leftJoystick = false;
  88842. }
  88843. VirtualJoystick._globalJoystickIndex++;
  88844. // By default left & right arrow keys are moving the X
  88845. // and up & down keys are moving the Y
  88846. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88847. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88848. this.reverseLeftRight = false;
  88849. this.reverseUpDown = false;
  88850. // collections of pointers
  88851. this._touches = new BABYLON.StringDictionary();
  88852. this.deltaPosition = BABYLON.Vector3.Zero();
  88853. this._joystickSensibility = 25;
  88854. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88855. this._onResize = function (evt) {
  88856. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88857. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88858. if (VirtualJoystick.vjCanvas) {
  88859. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88860. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88861. }
  88862. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88863. };
  88864. // injecting a canvas element on top of the canvas 3D game
  88865. if (!VirtualJoystick.vjCanvas) {
  88866. window.addEventListener("resize", this._onResize, false);
  88867. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88868. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88869. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88870. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88871. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88872. VirtualJoystick.vjCanvas.style.width = "100%";
  88873. VirtualJoystick.vjCanvas.style.height = "100%";
  88874. VirtualJoystick.vjCanvas.style.position = "absolute";
  88875. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88876. VirtualJoystick.vjCanvas.style.top = "0px";
  88877. VirtualJoystick.vjCanvas.style.left = "0px";
  88878. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88879. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88880. // Support for jQuery PEP polyfill
  88881. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88882. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88883. if (!context) {
  88884. throw new Error("Unable to create canvas for virtual joystick");
  88885. }
  88886. VirtualJoystick.vjCanvasContext = context;
  88887. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88888. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88889. document.body.appendChild(VirtualJoystick.vjCanvas);
  88890. }
  88891. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88892. this.pressed = false;
  88893. // default joystick color
  88894. this._joystickColor = "cyan";
  88895. this._joystickPointerID = -1;
  88896. // current joystick position
  88897. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88898. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88899. // origin joystick position
  88900. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88901. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88902. this._onPointerDownHandlerRef = function (evt) {
  88903. _this._onPointerDown(evt);
  88904. };
  88905. this._onPointerMoveHandlerRef = function (evt) {
  88906. _this._onPointerMove(evt);
  88907. };
  88908. this._onPointerUpHandlerRef = function (evt) {
  88909. _this._onPointerUp(evt);
  88910. };
  88911. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88912. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88913. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88914. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88915. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88916. evt.preventDefault(); // Disables system menu
  88917. }, false);
  88918. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88919. }
  88920. /**
  88921. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  88922. * @param newJoystickSensibility defines the new sensibility
  88923. */
  88924. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88925. this._joystickSensibility = newJoystickSensibility;
  88926. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88927. };
  88928. VirtualJoystick.prototype._onPointerDown = function (e) {
  88929. var positionOnScreenCondition;
  88930. e.preventDefault();
  88931. if (this._leftJoystick === true) {
  88932. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88933. }
  88934. else {
  88935. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88936. }
  88937. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88938. // First contact will be dedicated to the virtual joystick
  88939. this._joystickPointerID = e.pointerId;
  88940. this._joystickPointerStartPos.x = e.clientX;
  88941. this._joystickPointerStartPos.y = e.clientY;
  88942. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  88943. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  88944. this._deltaJoystickVector.x = 0;
  88945. this._deltaJoystickVector.y = 0;
  88946. this.pressed = true;
  88947. this._touches.add(e.pointerId.toString(), e);
  88948. }
  88949. else {
  88950. // You can only trigger the action buttons with a joystick declared
  88951. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  88952. this._action();
  88953. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  88954. }
  88955. }
  88956. };
  88957. VirtualJoystick.prototype._onPointerMove = function (e) {
  88958. // If the current pointer is the one associated to the joystick (first touch contact)
  88959. if (this._joystickPointerID == e.pointerId) {
  88960. this._joystickPointerPos.x = e.clientX;
  88961. this._joystickPointerPos.y = e.clientY;
  88962. this._deltaJoystickVector = this._joystickPointerPos.clone();
  88963. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  88964. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  88965. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  88966. switch (this._axisTargetedByLeftAndRight) {
  88967. case JoystickAxis.X:
  88968. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  88969. break;
  88970. case JoystickAxis.Y:
  88971. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  88972. break;
  88973. case JoystickAxis.Z:
  88974. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  88975. break;
  88976. }
  88977. var directionUpDown = this.reverseUpDown ? 1 : -1;
  88978. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  88979. switch (this._axisTargetedByUpAndDown) {
  88980. case JoystickAxis.X:
  88981. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  88982. break;
  88983. case JoystickAxis.Y:
  88984. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  88985. break;
  88986. case JoystickAxis.Z:
  88987. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  88988. break;
  88989. }
  88990. }
  88991. else {
  88992. var data = this._touches.get(e.pointerId.toString());
  88993. if (data) {
  88994. data.x = e.clientX;
  88995. data.y = e.clientY;
  88996. }
  88997. }
  88998. };
  88999. VirtualJoystick.prototype._onPointerUp = function (e) {
  89000. if (this._joystickPointerID == e.pointerId) {
  89001. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89002. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89003. this._joystickPointerID = -1;
  89004. this.pressed = false;
  89005. }
  89006. else {
  89007. var touch = this._touches.get(e.pointerId.toString());
  89008. if (touch) {
  89009. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89010. }
  89011. }
  89012. this._deltaJoystickVector.x = 0;
  89013. this._deltaJoystickVector.y = 0;
  89014. this._touches.remove(e.pointerId.toString());
  89015. };
  89016. /**
  89017. * Change the color of the virtual joystick
  89018. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89019. */
  89020. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89021. this._joystickColor = newColor;
  89022. };
  89023. /**
  89024. * Defines a callback to call when the joystick is touched
  89025. * @param action defines the callback
  89026. */
  89027. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89028. this._action = action;
  89029. };
  89030. /**
  89031. * Defines which axis you'd like to control for left & right
  89032. * @param axis defines the axis to use
  89033. */
  89034. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89035. switch (axis) {
  89036. case JoystickAxis.X:
  89037. case JoystickAxis.Y:
  89038. case JoystickAxis.Z:
  89039. this._axisTargetedByLeftAndRight = axis;
  89040. break;
  89041. default:
  89042. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89043. break;
  89044. }
  89045. };
  89046. /**
  89047. * Defines which axis you'd like to control for up & down
  89048. * @param axis defines the axis to use
  89049. */
  89050. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89051. switch (axis) {
  89052. case JoystickAxis.X:
  89053. case JoystickAxis.Y:
  89054. case JoystickAxis.Z:
  89055. this._axisTargetedByUpAndDown = axis;
  89056. break;
  89057. default:
  89058. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89059. break;
  89060. }
  89061. };
  89062. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89063. var _this = this;
  89064. if (this.pressed) {
  89065. this._touches.forEach(function (key, touch) {
  89066. if (touch.pointerId === _this._joystickPointerID) {
  89067. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89068. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89069. VirtualJoystick.vjCanvasContext.beginPath();
  89070. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89071. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89072. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89073. VirtualJoystick.vjCanvasContext.stroke();
  89074. VirtualJoystick.vjCanvasContext.closePath();
  89075. VirtualJoystick.vjCanvasContext.beginPath();
  89076. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89077. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89078. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89079. VirtualJoystick.vjCanvasContext.stroke();
  89080. VirtualJoystick.vjCanvasContext.closePath();
  89081. VirtualJoystick.vjCanvasContext.beginPath();
  89082. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89083. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89084. VirtualJoystick.vjCanvasContext.stroke();
  89085. VirtualJoystick.vjCanvasContext.closePath();
  89086. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89087. }
  89088. else {
  89089. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89090. VirtualJoystick.vjCanvasContext.beginPath();
  89091. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89092. VirtualJoystick.vjCanvasContext.beginPath();
  89093. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89094. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89095. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89096. VirtualJoystick.vjCanvasContext.stroke();
  89097. VirtualJoystick.vjCanvasContext.closePath();
  89098. touch.prevX = touch.x;
  89099. touch.prevY = touch.y;
  89100. }
  89101. ;
  89102. });
  89103. }
  89104. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89105. };
  89106. /**
  89107. * Release internal HTML canvas
  89108. */
  89109. VirtualJoystick.prototype.releaseCanvas = function () {
  89110. if (VirtualJoystick.vjCanvas) {
  89111. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89112. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89113. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89114. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89115. window.removeEventListener("resize", this._onResize);
  89116. document.body.removeChild(VirtualJoystick.vjCanvas);
  89117. VirtualJoystick.vjCanvas = null;
  89118. }
  89119. };
  89120. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89121. VirtualJoystick._globalJoystickIndex = 0;
  89122. return VirtualJoystick;
  89123. }());
  89124. BABYLON.VirtualJoystick = VirtualJoystick;
  89125. })(BABYLON || (BABYLON = {}));
  89126. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89127. var BABYLON;
  89128. (function (BABYLON) {
  89129. // We're mainly based on the logic defined into the FreeCamera code
  89130. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89131. __extends(VirtualJoysticksCamera, _super);
  89132. function VirtualJoysticksCamera(name, position, scene) {
  89133. var _this = _super.call(this, name, position, scene) || this;
  89134. _this.inputs.addVirtualJoystick();
  89135. return _this;
  89136. }
  89137. VirtualJoysticksCamera.prototype.getClassName = function () {
  89138. return "VirtualJoysticksCamera";
  89139. };
  89140. return VirtualJoysticksCamera;
  89141. }(BABYLON.FreeCamera));
  89142. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89143. })(BABYLON || (BABYLON = {}));
  89144. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89145. var BABYLON;
  89146. (function (BABYLON) {
  89147. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89148. function FreeCameraVirtualJoystickInput() {
  89149. }
  89150. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89151. return this._leftjoystick;
  89152. };
  89153. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89154. return this._rightjoystick;
  89155. };
  89156. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89157. if (this._leftjoystick) {
  89158. var camera = this.camera;
  89159. var speed = camera._computeLocalCameraSpeed() * 50;
  89160. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89161. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89162. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89163. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89164. if (!this._leftjoystick.pressed) {
  89165. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89166. }
  89167. if (!this._rightjoystick.pressed) {
  89168. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89169. }
  89170. }
  89171. };
  89172. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89173. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89174. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89175. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89176. this._leftjoystick.setJoystickSensibility(0.15);
  89177. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89178. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89179. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89180. this._rightjoystick.reverseUpDown = true;
  89181. this._rightjoystick.setJoystickSensibility(0.05);
  89182. this._rightjoystick.setJoystickColor("yellow");
  89183. };
  89184. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89185. this._leftjoystick.releaseCanvas();
  89186. this._rightjoystick.releaseCanvas();
  89187. };
  89188. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89189. return "FreeCameraVirtualJoystickInput";
  89190. };
  89191. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89192. return "virtualJoystick";
  89193. };
  89194. return FreeCameraVirtualJoystickInput;
  89195. }());
  89196. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89197. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89198. })(BABYLON || (BABYLON = {}));
  89199. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89200. var BABYLON;
  89201. (function (BABYLON) {
  89202. var SimplificationSettings = /** @class */ (function () {
  89203. function SimplificationSettings(quality, distance, optimizeMesh) {
  89204. this.quality = quality;
  89205. this.distance = distance;
  89206. this.optimizeMesh = optimizeMesh;
  89207. }
  89208. return SimplificationSettings;
  89209. }());
  89210. BABYLON.SimplificationSettings = SimplificationSettings;
  89211. var SimplificationQueue = /** @class */ (function () {
  89212. function SimplificationQueue() {
  89213. this.running = false;
  89214. this._simplificationArray = [];
  89215. }
  89216. SimplificationQueue.prototype.addTask = function (task) {
  89217. this._simplificationArray.push(task);
  89218. };
  89219. SimplificationQueue.prototype.executeNext = function () {
  89220. var task = this._simplificationArray.pop();
  89221. if (task) {
  89222. this.running = true;
  89223. this.runSimplification(task);
  89224. }
  89225. else {
  89226. this.running = false;
  89227. }
  89228. };
  89229. SimplificationQueue.prototype.runSimplification = function (task) {
  89230. var _this = this;
  89231. if (task.parallelProcessing) {
  89232. //parallel simplifier
  89233. task.settings.forEach(function (setting) {
  89234. var simplifier = _this.getSimplifier(task);
  89235. simplifier.simplify(setting, function (newMesh) {
  89236. task.mesh.addLODLevel(setting.distance, newMesh);
  89237. newMesh.isVisible = true;
  89238. //check if it is the last
  89239. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89240. //all done, run the success callback.
  89241. task.successCallback();
  89242. }
  89243. _this.executeNext();
  89244. });
  89245. });
  89246. }
  89247. else {
  89248. //single simplifier.
  89249. var simplifier = this.getSimplifier(task);
  89250. var runDecimation = function (setting, callback) {
  89251. simplifier.simplify(setting, function (newMesh) {
  89252. task.mesh.addLODLevel(setting.distance, newMesh);
  89253. newMesh.isVisible = true;
  89254. //run the next quality level
  89255. callback();
  89256. });
  89257. };
  89258. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89259. runDecimation(task.settings[loop.index], function () {
  89260. loop.executeNext();
  89261. });
  89262. }, function () {
  89263. //execution ended, run the success callback.
  89264. if (task.successCallback) {
  89265. task.successCallback();
  89266. }
  89267. _this.executeNext();
  89268. });
  89269. }
  89270. };
  89271. SimplificationQueue.prototype.getSimplifier = function (task) {
  89272. switch (task.simplificationType) {
  89273. case SimplificationType.QUADRATIC:
  89274. default:
  89275. return new QuadraticErrorSimplification(task.mesh);
  89276. }
  89277. };
  89278. return SimplificationQueue;
  89279. }());
  89280. BABYLON.SimplificationQueue = SimplificationQueue;
  89281. /**
  89282. * The implemented types of simplification
  89283. * At the moment only Quadratic Error Decimation is implemented
  89284. */
  89285. var SimplificationType;
  89286. (function (SimplificationType) {
  89287. /** Quadratic error decimation */
  89288. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89289. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89290. var DecimationTriangle = /** @class */ (function () {
  89291. function DecimationTriangle(vertices) {
  89292. this.vertices = vertices;
  89293. this.error = new Array(4);
  89294. this.deleted = false;
  89295. this.isDirty = false;
  89296. this.deletePending = false;
  89297. this.borderFactor = 0;
  89298. }
  89299. return DecimationTriangle;
  89300. }());
  89301. BABYLON.DecimationTriangle = DecimationTriangle;
  89302. var DecimationVertex = /** @class */ (function () {
  89303. function DecimationVertex(position, id) {
  89304. this.position = position;
  89305. this.id = id;
  89306. this.isBorder = true;
  89307. this.q = new QuadraticMatrix();
  89308. this.triangleCount = 0;
  89309. this.triangleStart = 0;
  89310. this.originalOffsets = [];
  89311. }
  89312. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89313. this.position.copyFrom(newPosition);
  89314. };
  89315. return DecimationVertex;
  89316. }());
  89317. BABYLON.DecimationVertex = DecimationVertex;
  89318. var QuadraticMatrix = /** @class */ (function () {
  89319. function QuadraticMatrix(data) {
  89320. this.data = new Array(10);
  89321. for (var i = 0; i < 10; ++i) {
  89322. if (data && data[i]) {
  89323. this.data[i] = data[i];
  89324. }
  89325. else {
  89326. this.data[i] = 0;
  89327. }
  89328. }
  89329. }
  89330. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89331. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89332. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89333. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89334. return det;
  89335. };
  89336. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89337. for (var i = 0; i < 10; ++i) {
  89338. this.data[i] += matrix.data[i];
  89339. }
  89340. };
  89341. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89342. for (var i = 0; i < 10; ++i) {
  89343. this.data[i] += data[i];
  89344. }
  89345. };
  89346. QuadraticMatrix.prototype.add = function (matrix) {
  89347. var m = new QuadraticMatrix();
  89348. for (var i = 0; i < 10; ++i) {
  89349. m.data[i] = this.data[i] + matrix.data[i];
  89350. }
  89351. return m;
  89352. };
  89353. QuadraticMatrix.FromData = function (a, b, c, d) {
  89354. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89355. };
  89356. //returning an array to avoid garbage collection
  89357. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89358. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89359. };
  89360. return QuadraticMatrix;
  89361. }());
  89362. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89363. var Reference = /** @class */ (function () {
  89364. function Reference(vertexId, triangleId) {
  89365. this.vertexId = vertexId;
  89366. this.triangleId = triangleId;
  89367. }
  89368. return Reference;
  89369. }());
  89370. BABYLON.Reference = Reference;
  89371. /**
  89372. * An implementation of the Quadratic Error simplification algorithm.
  89373. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89374. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89375. * @author RaananW
  89376. */
  89377. var QuadraticErrorSimplification = /** @class */ (function () {
  89378. function QuadraticErrorSimplification(_mesh) {
  89379. this._mesh = _mesh;
  89380. this.syncIterations = 5000;
  89381. this.aggressiveness = 7;
  89382. this.decimationIterations = 100;
  89383. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89384. }
  89385. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89386. var _this = this;
  89387. this.initDecimatedMesh();
  89388. //iterating through the submeshes array, one after the other.
  89389. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89390. _this.initWithMesh(loop.index, function () {
  89391. _this.runDecimation(settings, loop.index, function () {
  89392. loop.executeNext();
  89393. });
  89394. }, settings.optimizeMesh);
  89395. }, function () {
  89396. setTimeout(function () {
  89397. successCallback(_this._reconstructedMesh);
  89398. }, 0);
  89399. });
  89400. };
  89401. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89402. var _this = this;
  89403. var targetCount = ~~(this.triangles.length * settings.quality);
  89404. var deletedTriangles = 0;
  89405. var triangleCount = this.triangles.length;
  89406. var iterationFunction = function (iteration, callback) {
  89407. setTimeout(function () {
  89408. if (iteration % 5 === 0) {
  89409. _this.updateMesh(iteration === 0);
  89410. }
  89411. for (var i = 0; i < _this.triangles.length; ++i) {
  89412. _this.triangles[i].isDirty = false;
  89413. }
  89414. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89415. var trianglesIterator = function (i) {
  89416. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89417. var t = _this.triangles[tIdx];
  89418. if (!t)
  89419. return;
  89420. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89421. return;
  89422. }
  89423. for (var j = 0; j < 3; ++j) {
  89424. if (t.error[j] < threshold) {
  89425. var deleted0 = [];
  89426. var deleted1 = [];
  89427. var v0 = t.vertices[j];
  89428. var v1 = t.vertices[(j + 1) % 3];
  89429. if (v0.isBorder || v1.isBorder)
  89430. continue;
  89431. var p = BABYLON.Vector3.Zero();
  89432. var n = BABYLON.Vector3.Zero();
  89433. var uv = BABYLON.Vector2.Zero();
  89434. var color = new BABYLON.Color4(0, 0, 0, 1);
  89435. _this.calculateError(v0, v1, p, n, uv, color);
  89436. var delTr = new Array();
  89437. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89438. continue;
  89439. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89440. continue;
  89441. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89442. continue;
  89443. var uniqueArray = new Array();
  89444. delTr.forEach(function (deletedT) {
  89445. if (uniqueArray.indexOf(deletedT) === -1) {
  89446. deletedT.deletePending = true;
  89447. uniqueArray.push(deletedT);
  89448. }
  89449. });
  89450. if (uniqueArray.length % 2 !== 0) {
  89451. continue;
  89452. }
  89453. v0.q = v1.q.add(v0.q);
  89454. v0.updatePosition(p);
  89455. var tStart = _this.references.length;
  89456. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89457. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89458. var tCount = _this.references.length - tStart;
  89459. if (tCount <= v0.triangleCount) {
  89460. if (tCount) {
  89461. for (var c = 0; c < tCount; c++) {
  89462. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89463. }
  89464. }
  89465. }
  89466. else {
  89467. v0.triangleStart = tStart;
  89468. }
  89469. v0.triangleCount = tCount;
  89470. break;
  89471. }
  89472. }
  89473. };
  89474. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89475. }, 0);
  89476. };
  89477. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89478. if (triangleCount - deletedTriangles <= targetCount)
  89479. loop.breakLoop();
  89480. else {
  89481. iterationFunction(loop.index, function () {
  89482. loop.executeNext();
  89483. });
  89484. }
  89485. }, function () {
  89486. setTimeout(function () {
  89487. //reconstruct this part of the mesh
  89488. _this.reconstructMesh(submeshIndex);
  89489. successCallback();
  89490. }, 0);
  89491. });
  89492. };
  89493. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89494. var _this = this;
  89495. this.vertices = [];
  89496. this.triangles = [];
  89497. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89498. var indices = this._mesh.getIndices();
  89499. var submesh = this._mesh.subMeshes[submeshIndex];
  89500. var findInVertices = function (positionToSearch) {
  89501. if (optimizeMesh) {
  89502. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89503. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89504. return _this.vertices[ii];
  89505. }
  89506. }
  89507. }
  89508. return null;
  89509. };
  89510. var vertexReferences = [];
  89511. var vertexInit = function (i) {
  89512. if (!positionData) {
  89513. return;
  89514. }
  89515. var offset = i + submesh.verticesStart;
  89516. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89517. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89518. vertex.originalOffsets.push(offset);
  89519. if (vertex.id === _this.vertices.length) {
  89520. _this.vertices.push(vertex);
  89521. }
  89522. vertexReferences.push(vertex.id);
  89523. };
  89524. //var totalVertices = mesh.getTotalVertices();
  89525. var totalVertices = submesh.verticesCount;
  89526. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89527. var indicesInit = function (i) {
  89528. if (!indices) {
  89529. return;
  89530. }
  89531. var offset = (submesh.indexStart / 3) + i;
  89532. var pos = (offset * 3);
  89533. var i0 = indices[pos + 0];
  89534. var i1 = indices[pos + 1];
  89535. var i2 = indices[pos + 2];
  89536. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89537. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89538. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89539. var triangle = new DecimationTriangle([v0, v1, v2]);
  89540. triangle.originalOffset = pos;
  89541. _this.triangles.push(triangle);
  89542. };
  89543. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89544. _this.init(callback);
  89545. });
  89546. });
  89547. };
  89548. QuadraticErrorSimplification.prototype.init = function (callback) {
  89549. var _this = this;
  89550. var triangleInit1 = function (i) {
  89551. var t = _this.triangles[i];
  89552. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89553. for (var j = 0; j < 3; j++) {
  89554. 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))));
  89555. }
  89556. };
  89557. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89558. var triangleInit2 = function (i) {
  89559. var t = _this.triangles[i];
  89560. for (var j = 0; j < 3; ++j) {
  89561. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89562. }
  89563. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89564. };
  89565. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89566. callback();
  89567. });
  89568. });
  89569. };
  89570. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89571. var newTriangles = [];
  89572. var i;
  89573. for (i = 0; i < this.vertices.length; ++i) {
  89574. this.vertices[i].triangleCount = 0;
  89575. }
  89576. var t;
  89577. var j;
  89578. for (i = 0; i < this.triangles.length; ++i) {
  89579. if (!this.triangles[i].deleted) {
  89580. t = this.triangles[i];
  89581. for (j = 0; j < 3; ++j) {
  89582. t.vertices[j].triangleCount = 1;
  89583. }
  89584. newTriangles.push(t);
  89585. }
  89586. }
  89587. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89588. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89589. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89590. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89591. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89592. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89593. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89594. var vertexCount = 0;
  89595. for (i = 0; i < this.vertices.length; ++i) {
  89596. var vertex = this.vertices[i];
  89597. vertex.id = vertexCount;
  89598. if (vertex.triangleCount) {
  89599. vertex.originalOffsets.forEach(function (originalOffset) {
  89600. if (!normalData) {
  89601. return;
  89602. }
  89603. newPositionData.push(vertex.position.x);
  89604. newPositionData.push(vertex.position.y);
  89605. newPositionData.push(vertex.position.z);
  89606. newNormalData.push(normalData[originalOffset * 3]);
  89607. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89608. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89609. if (uvs && uvs.length) {
  89610. newUVsData.push(uvs[(originalOffset * 2)]);
  89611. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89612. }
  89613. else if (colorsData && colorsData.length) {
  89614. newColorsData.push(colorsData[(originalOffset * 4)]);
  89615. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89616. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89617. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89618. }
  89619. ++vertexCount;
  89620. });
  89621. }
  89622. }
  89623. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89624. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89625. var submeshesArray = this._reconstructedMesh.subMeshes;
  89626. this._reconstructedMesh.subMeshes = [];
  89627. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89628. var originalIndices = this._mesh.getIndices();
  89629. for (i = 0; i < newTriangles.length; ++i) {
  89630. t = newTriangles[i]; //now get the new referencing point for each vertex
  89631. [0, 1, 2].forEach(function (idx) {
  89632. var id = originalIndices[t.originalOffset + idx];
  89633. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89634. if (offset < 0)
  89635. offset = 0;
  89636. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89637. });
  89638. }
  89639. //overwriting the old vertex buffers and indices.
  89640. this._reconstructedMesh.setIndices(newIndicesArray);
  89641. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89642. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89643. if (newUVsData.length > 0)
  89644. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89645. if (newColorsData.length > 0)
  89646. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89647. //create submesh
  89648. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89649. if (submeshIndex > 0) {
  89650. this._reconstructedMesh.subMeshes = [];
  89651. submeshesArray.forEach(function (submesh) {
  89652. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89653. });
  89654. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89655. }
  89656. };
  89657. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89658. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89659. this._reconstructedMesh.material = this._mesh.material;
  89660. this._reconstructedMesh.parent = this._mesh.parent;
  89661. this._reconstructedMesh.isVisible = false;
  89662. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89663. };
  89664. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89665. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89666. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89667. if (t.deleted)
  89668. continue;
  89669. var s = this.references[vertex1.triangleStart + i].vertexId;
  89670. var v1 = t.vertices[(s + 1) % 3];
  89671. var v2 = t.vertices[(s + 2) % 3];
  89672. if ((v1 === vertex2 || v2 === vertex2)) {
  89673. deletedArray[i] = true;
  89674. delTr.push(t);
  89675. continue;
  89676. }
  89677. var d1 = v1.position.subtract(point);
  89678. d1 = d1.normalize();
  89679. var d2 = v2.position.subtract(point);
  89680. d2 = d2.normalize();
  89681. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89682. return true;
  89683. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89684. deletedArray[i] = false;
  89685. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89686. return true;
  89687. }
  89688. return false;
  89689. };
  89690. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89691. var newDeleted = deletedTriangles;
  89692. for (var i = 0; i < vertex.triangleCount; ++i) {
  89693. var ref = this.references[vertex.triangleStart + i];
  89694. var t = this.triangles[ref.triangleId];
  89695. if (t.deleted)
  89696. continue;
  89697. if (deletedArray[i] && t.deletePending) {
  89698. t.deleted = true;
  89699. newDeleted++;
  89700. continue;
  89701. }
  89702. t.vertices[ref.vertexId] = origVertex;
  89703. t.isDirty = true;
  89704. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89705. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89706. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89707. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89708. this.references.push(ref);
  89709. }
  89710. return newDeleted;
  89711. };
  89712. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89713. for (var i = 0; i < this.vertices.length; ++i) {
  89714. var vCount = [];
  89715. var vId = [];
  89716. var v = this.vertices[i];
  89717. var j;
  89718. for (j = 0; j < v.triangleCount; ++j) {
  89719. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89720. for (var ii = 0; ii < 3; ii++) {
  89721. var ofs = 0;
  89722. var vv = triangle.vertices[ii];
  89723. while (ofs < vCount.length) {
  89724. if (vId[ofs] === vv.id)
  89725. break;
  89726. ++ofs;
  89727. }
  89728. if (ofs === vCount.length) {
  89729. vCount.push(1);
  89730. vId.push(vv.id);
  89731. }
  89732. else {
  89733. vCount[ofs]++;
  89734. }
  89735. }
  89736. }
  89737. for (j = 0; j < vCount.length; ++j) {
  89738. if (vCount[j] === 1) {
  89739. this.vertices[vId[j]].isBorder = true;
  89740. }
  89741. else {
  89742. this.vertices[vId[j]].isBorder = false;
  89743. }
  89744. }
  89745. }
  89746. };
  89747. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89748. if (identifyBorders === void 0) { identifyBorders = false; }
  89749. var i;
  89750. if (!identifyBorders) {
  89751. var newTrianglesVector = [];
  89752. for (i = 0; i < this.triangles.length; ++i) {
  89753. if (!this.triangles[i].deleted) {
  89754. newTrianglesVector.push(this.triangles[i]);
  89755. }
  89756. }
  89757. this.triangles = newTrianglesVector;
  89758. }
  89759. for (i = 0; i < this.vertices.length; ++i) {
  89760. this.vertices[i].triangleCount = 0;
  89761. this.vertices[i].triangleStart = 0;
  89762. }
  89763. var t;
  89764. var j;
  89765. var v;
  89766. for (i = 0; i < this.triangles.length; ++i) {
  89767. t = this.triangles[i];
  89768. for (j = 0; j < 3; ++j) {
  89769. v = t.vertices[j];
  89770. v.triangleCount++;
  89771. }
  89772. }
  89773. var tStart = 0;
  89774. for (i = 0; i < this.vertices.length; ++i) {
  89775. this.vertices[i].triangleStart = tStart;
  89776. tStart += this.vertices[i].triangleCount;
  89777. this.vertices[i].triangleCount = 0;
  89778. }
  89779. var newReferences = new Array(this.triangles.length * 3);
  89780. for (i = 0; i < this.triangles.length; ++i) {
  89781. t = this.triangles[i];
  89782. for (j = 0; j < 3; ++j) {
  89783. v = t.vertices[j];
  89784. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89785. v.triangleCount++;
  89786. }
  89787. }
  89788. this.references = newReferences;
  89789. if (identifyBorders) {
  89790. this.identifyBorder();
  89791. }
  89792. };
  89793. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89794. var x = point.x;
  89795. var y = point.y;
  89796. var z = point.z;
  89797. 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
  89798. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89799. };
  89800. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89801. var q = vertex1.q.add(vertex2.q);
  89802. var border = vertex1.isBorder && vertex2.isBorder;
  89803. var error = 0;
  89804. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89805. if (qDet !== 0 && !border) {
  89806. if (!pointResult) {
  89807. pointResult = BABYLON.Vector3.Zero();
  89808. }
  89809. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89810. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89811. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89812. error = this.vertexError(q, pointResult);
  89813. }
  89814. else {
  89815. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89816. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89817. var error1 = this.vertexError(q, vertex1.position);
  89818. var error2 = this.vertexError(q, vertex2.position);
  89819. var error3 = this.vertexError(q, p3);
  89820. error = Math.min(error1, error2, error3);
  89821. if (error === error1) {
  89822. if (pointResult) {
  89823. pointResult.copyFrom(vertex1.position);
  89824. }
  89825. }
  89826. else if (error === error2) {
  89827. if (pointResult) {
  89828. pointResult.copyFrom(vertex2.position);
  89829. }
  89830. }
  89831. else {
  89832. if (pointResult) {
  89833. pointResult.copyFrom(p3);
  89834. }
  89835. }
  89836. }
  89837. return error;
  89838. };
  89839. return QuadraticErrorSimplification;
  89840. }());
  89841. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89842. })(BABYLON || (BABYLON = {}));
  89843. //# sourceMappingURL=babylon.meshSimplification.js.map
  89844. var BABYLON;
  89845. (function (BABYLON) {
  89846. var MeshLODLevel = /** @class */ (function () {
  89847. function MeshLODLevel(distance, mesh) {
  89848. this.distance = distance;
  89849. this.mesh = mesh;
  89850. }
  89851. return MeshLODLevel;
  89852. }());
  89853. BABYLON.MeshLODLevel = MeshLODLevel;
  89854. })(BABYLON || (BABYLON = {}));
  89855. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89856. var BABYLON;
  89857. (function (BABYLON) {
  89858. /**
  89859. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89860. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89861. */
  89862. var SceneOptimization = /** @class */ (function () {
  89863. /**
  89864. * Creates the SceneOptimization object
  89865. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89866. * @param desc defines the description associated with the optimization
  89867. */
  89868. function SceneOptimization(
  89869. /**
  89870. * Defines the priority of this optimization (0 by default which means first in the list)
  89871. */
  89872. priority) {
  89873. if (priority === void 0) { priority = 0; }
  89874. this.priority = priority;
  89875. }
  89876. /**
  89877. * Gets a string describing the action executed by the current optimization
  89878. * @returns description string
  89879. */
  89880. SceneOptimization.prototype.getDescription = function () {
  89881. return "";
  89882. };
  89883. /**
  89884. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89885. * @param scene defines the current scene where to apply this optimization
  89886. * @param optimizer defines the current optimizer
  89887. * @returns true if everything that can be done was applied
  89888. */
  89889. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89890. return true;
  89891. };
  89892. ;
  89893. return SceneOptimization;
  89894. }());
  89895. BABYLON.SceneOptimization = SceneOptimization;
  89896. /**
  89897. * Defines an optimization used to reduce the size of render target textures
  89898. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89899. */
  89900. var TextureOptimization = /** @class */ (function (_super) {
  89901. __extends(TextureOptimization, _super);
  89902. /**
  89903. * Creates the TextureOptimization object
  89904. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89905. * @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
  89906. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89907. */
  89908. function TextureOptimization(
  89909. /**
  89910. * Defines the priority of this optimization (0 by default which means first in the list)
  89911. */
  89912. priority,
  89913. /**
  89914. * 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
  89915. */
  89916. maximumSize,
  89917. /**
  89918. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89919. */
  89920. step) {
  89921. if (priority === void 0) { priority = 0; }
  89922. if (maximumSize === void 0) { maximumSize = 1024; }
  89923. if (step === void 0) { step = 0.5; }
  89924. var _this = _super.call(this, priority) || this;
  89925. _this.priority = priority;
  89926. _this.maximumSize = maximumSize;
  89927. _this.step = step;
  89928. return _this;
  89929. }
  89930. /**
  89931. * Gets a string describing the action executed by the current optimization
  89932. * @returns description string
  89933. */
  89934. TextureOptimization.prototype.getDescription = function () {
  89935. return "Reducing render target texture size to " + this.maximumSize;
  89936. };
  89937. /**
  89938. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89939. * @param scene defines the current scene where to apply this optimization
  89940. * @param optimizer defines the current optimizer
  89941. * @returns true if everything that can be done was applied
  89942. */
  89943. TextureOptimization.prototype.apply = function (scene, optimizer) {
  89944. var allDone = true;
  89945. for (var index = 0; index < scene.textures.length; index++) {
  89946. var texture = scene.textures[index];
  89947. if (!texture.canRescale || texture.getContext) {
  89948. continue;
  89949. }
  89950. var currentSize = texture.getSize();
  89951. var maxDimension = Math.max(currentSize.width, currentSize.height);
  89952. if (maxDimension > this.maximumSize) {
  89953. texture.scale(this.step);
  89954. allDone = false;
  89955. }
  89956. }
  89957. return allDone;
  89958. };
  89959. return TextureOptimization;
  89960. }(SceneOptimization));
  89961. BABYLON.TextureOptimization = TextureOptimization;
  89962. /**
  89963. * Defines an optimization used to increase or decrease the rendering resolution
  89964. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89965. */
  89966. var HardwareScalingOptimization = /** @class */ (function (_super) {
  89967. __extends(HardwareScalingOptimization, _super);
  89968. /**
  89969. * Creates the HardwareScalingOptimization object
  89970. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89971. * @param maximumScale defines the maximum scale to use (2 by default)
  89972. * @param step defines the step to use between two passes (0.5 by default)
  89973. */
  89974. function HardwareScalingOptimization(
  89975. /**
  89976. * Defines the priority of this optimization (0 by default which means first in the list)
  89977. */
  89978. priority,
  89979. /**
  89980. * Defines the maximum scale to use (2 by default)
  89981. */
  89982. maximumScale,
  89983. /**
  89984. * Defines the step to use between two passes (0.5 by default)
  89985. */
  89986. step) {
  89987. if (priority === void 0) { priority = 0; }
  89988. if (maximumScale === void 0) { maximumScale = 2; }
  89989. if (step === void 0) { step = 0.25; }
  89990. var _this = _super.call(this, priority) || this;
  89991. _this.priority = priority;
  89992. _this.maximumScale = maximumScale;
  89993. _this.step = step;
  89994. _this._currentScale = -1;
  89995. _this._directionOffset = 1;
  89996. return _this;
  89997. }
  89998. /**
  89999. * Gets a string describing the action executed by the current optimization
  90000. * @return description string
  90001. */
  90002. HardwareScalingOptimization.prototype.getDescription = function () {
  90003. return "Setting hardware scaling level to " + this._currentScale;
  90004. };
  90005. /**
  90006. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90007. * @param scene defines the current scene where to apply this optimization
  90008. * @param optimizer defines the current optimizer
  90009. * @returns true if everything that can be done was applied
  90010. */
  90011. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90012. if (this._currentScale === -1) {
  90013. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90014. if (this._currentScale > this.maximumScale) {
  90015. this._directionOffset = -1;
  90016. }
  90017. }
  90018. this._currentScale += this._directionOffset * this.step;
  90019. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90020. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90021. };
  90022. ;
  90023. return HardwareScalingOptimization;
  90024. }(SceneOptimization));
  90025. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90026. /**
  90027. * Defines an optimization used to remove shadows
  90028. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90029. */
  90030. var ShadowsOptimization = /** @class */ (function (_super) {
  90031. __extends(ShadowsOptimization, _super);
  90032. function ShadowsOptimization() {
  90033. return _super !== null && _super.apply(this, arguments) || this;
  90034. }
  90035. /**
  90036. * Gets a string describing the action executed by the current optimization
  90037. * @return description string
  90038. */
  90039. ShadowsOptimization.prototype.getDescription = function () {
  90040. return "Turning shadows on/off";
  90041. };
  90042. /**
  90043. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90044. * @param scene defines the current scene where to apply this optimization
  90045. * @param optimizer defines the current optimizer
  90046. * @returns true if everything that can be done was applied
  90047. */
  90048. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90049. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90050. return true;
  90051. };
  90052. ;
  90053. return ShadowsOptimization;
  90054. }(SceneOptimization));
  90055. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90056. /**
  90057. * Defines an optimization used to turn post-processes off
  90058. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90059. */
  90060. var PostProcessesOptimization = /** @class */ (function (_super) {
  90061. __extends(PostProcessesOptimization, _super);
  90062. function PostProcessesOptimization() {
  90063. return _super !== null && _super.apply(this, arguments) || this;
  90064. }
  90065. /**
  90066. * Gets a string describing the action executed by the current optimization
  90067. * @return description string
  90068. */
  90069. PostProcessesOptimization.prototype.getDescription = function () {
  90070. return "Turning post-processes on/off";
  90071. };
  90072. /**
  90073. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90074. * @param scene defines the current scene where to apply this optimization
  90075. * @param optimizer defines the current optimizer
  90076. * @returns true if everything that can be done was applied
  90077. */
  90078. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90079. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90080. return true;
  90081. };
  90082. ;
  90083. return PostProcessesOptimization;
  90084. }(SceneOptimization));
  90085. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90086. /**
  90087. * Defines an optimization used to turn lens flares off
  90088. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90089. */
  90090. var LensFlaresOptimization = /** @class */ (function (_super) {
  90091. __extends(LensFlaresOptimization, _super);
  90092. function LensFlaresOptimization() {
  90093. return _super !== null && _super.apply(this, arguments) || this;
  90094. }
  90095. /**
  90096. * Gets a string describing the action executed by the current optimization
  90097. * @return description string
  90098. */
  90099. LensFlaresOptimization.prototype.getDescription = function () {
  90100. return "Turning lens flares on/off";
  90101. };
  90102. /**
  90103. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90104. * @param scene defines the current scene where to apply this optimization
  90105. * @param optimizer defines the current optimizer
  90106. * @returns true if everything that can be done was applied
  90107. */
  90108. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90109. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90110. return true;
  90111. };
  90112. ;
  90113. return LensFlaresOptimization;
  90114. }(SceneOptimization));
  90115. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90116. /**
  90117. * Defines an optimization based on user defined callback.
  90118. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90119. */
  90120. var CustomOptimization = /** @class */ (function (_super) {
  90121. __extends(CustomOptimization, _super);
  90122. function CustomOptimization() {
  90123. return _super !== null && _super.apply(this, arguments) || this;
  90124. }
  90125. /**
  90126. * Gets a string describing the action executed by the current optimization
  90127. * @returns description string
  90128. */
  90129. CustomOptimization.prototype.getDescription = function () {
  90130. if (this.onGetDescription) {
  90131. return this.onGetDescription();
  90132. }
  90133. return "Running user defined callback";
  90134. };
  90135. /**
  90136. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90137. * @param scene defines the current scene where to apply this optimization
  90138. * @param optimizer defines the current optimizer
  90139. * @returns true if everything that can be done was applied
  90140. */
  90141. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90142. if (this.onApply) {
  90143. return this.onApply(scene, optimizer);
  90144. }
  90145. return true;
  90146. };
  90147. ;
  90148. return CustomOptimization;
  90149. }(SceneOptimization));
  90150. BABYLON.CustomOptimization = CustomOptimization;
  90151. /**
  90152. * Defines an optimization used to turn particles off
  90153. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90154. */
  90155. var ParticlesOptimization = /** @class */ (function (_super) {
  90156. __extends(ParticlesOptimization, _super);
  90157. function ParticlesOptimization() {
  90158. return _super !== null && _super.apply(this, arguments) || this;
  90159. }
  90160. /**
  90161. * Gets a string describing the action executed by the current optimization
  90162. * @return description string
  90163. */
  90164. ParticlesOptimization.prototype.getDescription = function () {
  90165. return "Turning particles on/off";
  90166. };
  90167. /**
  90168. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90169. * @param scene defines the current scene where to apply this optimization
  90170. * @param optimizer defines the current optimizer
  90171. * @returns true if everything that can be done was applied
  90172. */
  90173. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90174. scene.particlesEnabled = optimizer.isInImprovementMode;
  90175. return true;
  90176. };
  90177. ;
  90178. return ParticlesOptimization;
  90179. }(SceneOptimization));
  90180. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90181. /**
  90182. * Defines an optimization used to turn render targets off
  90183. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90184. */
  90185. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90186. __extends(RenderTargetsOptimization, _super);
  90187. function RenderTargetsOptimization() {
  90188. return _super !== null && _super.apply(this, arguments) || this;
  90189. }
  90190. /**
  90191. * Gets a string describing the action executed by the current optimization
  90192. * @return description string
  90193. */
  90194. RenderTargetsOptimization.prototype.getDescription = function () {
  90195. return "Turning render targets off";
  90196. };
  90197. /**
  90198. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90199. * @param scene defines the current scene where to apply this optimization
  90200. * @param optimizer defines the current optimizer
  90201. * @returns true if everything that can be done was applied
  90202. */
  90203. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90204. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90205. return true;
  90206. };
  90207. ;
  90208. return RenderTargetsOptimization;
  90209. }(SceneOptimization));
  90210. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90211. /**
  90212. * Defines an optimization used to merge meshes with compatible materials
  90213. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90214. */
  90215. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90216. __extends(MergeMeshesOptimization, _super);
  90217. function MergeMeshesOptimization() {
  90218. var _this = _super !== null && _super.apply(this, arguments) || this;
  90219. _this._canBeMerged = function (abstractMesh) {
  90220. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90221. return false;
  90222. }
  90223. var mesh = abstractMesh;
  90224. if (!mesh.isVisible || !mesh.isEnabled()) {
  90225. return false;
  90226. }
  90227. if (mesh.instances.length > 0) {
  90228. return false;
  90229. }
  90230. if (mesh.skeleton || mesh.hasLODLevels) {
  90231. return false;
  90232. }
  90233. if (mesh.parent) {
  90234. return false;
  90235. }
  90236. return true;
  90237. };
  90238. return _this;
  90239. }
  90240. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90241. /**
  90242. * Gets or sets a boolean which defines if optimization octree has to be updated
  90243. */
  90244. get: function () {
  90245. return MergeMeshesOptimization._UpdateSelectionTree;
  90246. },
  90247. /**
  90248. * Gets or sets a boolean which defines if optimization octree has to be updated
  90249. */
  90250. set: function (value) {
  90251. MergeMeshesOptimization._UpdateSelectionTree = value;
  90252. },
  90253. enumerable: true,
  90254. configurable: true
  90255. });
  90256. /**
  90257. * Gets a string describing the action executed by the current optimization
  90258. * @return description string
  90259. */
  90260. MergeMeshesOptimization.prototype.getDescription = function () {
  90261. return "Merging similar meshes together";
  90262. };
  90263. /**
  90264. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90265. * @param scene defines the current scene where to apply this optimization
  90266. * @param optimizer defines the current optimizer
  90267. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90268. * @returns true if everything that can be done was applied
  90269. */
  90270. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90271. var globalPool = scene.meshes.slice(0);
  90272. var globalLength = globalPool.length;
  90273. for (var index = 0; index < globalLength; index++) {
  90274. var currentPool = new Array();
  90275. var current = globalPool[index];
  90276. // Checks
  90277. if (!this._canBeMerged(current)) {
  90278. continue;
  90279. }
  90280. currentPool.push(current);
  90281. // Find compatible meshes
  90282. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90283. var otherMesh = globalPool[subIndex];
  90284. if (!this._canBeMerged(otherMesh)) {
  90285. continue;
  90286. }
  90287. if (otherMesh.material !== current.material) {
  90288. continue;
  90289. }
  90290. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90291. continue;
  90292. }
  90293. currentPool.push(otherMesh);
  90294. globalLength--;
  90295. globalPool.splice(subIndex, 1);
  90296. subIndex--;
  90297. }
  90298. if (currentPool.length < 2) {
  90299. continue;
  90300. }
  90301. // Merge meshes
  90302. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90303. }
  90304. if (updateSelectionTree != undefined) {
  90305. if (updateSelectionTree) {
  90306. scene.createOrUpdateSelectionOctree();
  90307. }
  90308. }
  90309. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90310. scene.createOrUpdateSelectionOctree();
  90311. }
  90312. return true;
  90313. };
  90314. ;
  90315. MergeMeshesOptimization._UpdateSelectionTree = false;
  90316. return MergeMeshesOptimization;
  90317. }(SceneOptimization));
  90318. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90319. /**
  90320. * Defines a list of options used by SceneOptimizer
  90321. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90322. */
  90323. var SceneOptimizerOptions = /** @class */ (function () {
  90324. /**
  90325. * Creates a new list of options used by SceneOptimizer
  90326. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90327. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90328. */
  90329. function SceneOptimizerOptions(
  90330. /**
  90331. * Defines the target frame rate to reach (60 by default)
  90332. */
  90333. targetFrameRate,
  90334. /**
  90335. * Defines the interval between two checkes (2000ms by default)
  90336. */
  90337. trackerDuration) {
  90338. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90339. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90340. this.targetFrameRate = targetFrameRate;
  90341. this.trackerDuration = trackerDuration;
  90342. /**
  90343. * Gets the list of optimizations to apply
  90344. */
  90345. this.optimizations = new Array();
  90346. }
  90347. /**
  90348. * Add a new optimization
  90349. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90350. * @returns the current SceneOptimizerOptions
  90351. */
  90352. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90353. this.optimizations.push(optimization);
  90354. return this;
  90355. };
  90356. /**
  90357. * Add a new custom optimization
  90358. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90359. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90360. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90361. * @returns the current SceneOptimizerOptions
  90362. */
  90363. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90364. if (priority === void 0) { priority = 0; }
  90365. var optimization = new CustomOptimization(priority);
  90366. optimization.onApply = onApply;
  90367. optimization.onGetDescription = onGetDescription;
  90368. this.optimizations.push(optimization);
  90369. return this;
  90370. };
  90371. /**
  90372. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90373. * @param targetFrameRate defines the target frame rate (60 by default)
  90374. * @returns a SceneOptimizerOptions object
  90375. */
  90376. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90377. var result = new SceneOptimizerOptions(targetFrameRate);
  90378. var priority = 0;
  90379. result.addOptimization(new MergeMeshesOptimization(priority));
  90380. result.addOptimization(new ShadowsOptimization(priority));
  90381. result.addOptimization(new LensFlaresOptimization(priority));
  90382. // Next priority
  90383. priority++;
  90384. result.addOptimization(new PostProcessesOptimization(priority));
  90385. result.addOptimization(new ParticlesOptimization(priority));
  90386. // Next priority
  90387. priority++;
  90388. result.addOptimization(new TextureOptimization(priority, 1024));
  90389. return result;
  90390. };
  90391. /**
  90392. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90393. * @param targetFrameRate defines the target frame rate (60 by default)
  90394. * @returns a SceneOptimizerOptions object
  90395. */
  90396. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90397. var result = new SceneOptimizerOptions(targetFrameRate);
  90398. var priority = 0;
  90399. result.addOptimization(new MergeMeshesOptimization(priority));
  90400. result.addOptimization(new ShadowsOptimization(priority));
  90401. result.addOptimization(new LensFlaresOptimization(priority));
  90402. // Next priority
  90403. priority++;
  90404. result.addOptimization(new PostProcessesOptimization(priority));
  90405. result.addOptimization(new ParticlesOptimization(priority));
  90406. // Next priority
  90407. priority++;
  90408. result.addOptimization(new TextureOptimization(priority, 512));
  90409. // Next priority
  90410. priority++;
  90411. result.addOptimization(new RenderTargetsOptimization(priority));
  90412. // Next priority
  90413. priority++;
  90414. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90415. return result;
  90416. };
  90417. /**
  90418. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90419. * @param targetFrameRate defines the target frame rate (60 by default)
  90420. * @returns a SceneOptimizerOptions object
  90421. */
  90422. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90423. var result = new SceneOptimizerOptions(targetFrameRate);
  90424. var priority = 0;
  90425. result.addOptimization(new MergeMeshesOptimization(priority));
  90426. result.addOptimization(new ShadowsOptimization(priority));
  90427. result.addOptimization(new LensFlaresOptimization(priority));
  90428. // Next priority
  90429. priority++;
  90430. result.addOptimization(new PostProcessesOptimization(priority));
  90431. result.addOptimization(new ParticlesOptimization(priority));
  90432. // Next priority
  90433. priority++;
  90434. result.addOptimization(new TextureOptimization(priority, 256));
  90435. // Next priority
  90436. priority++;
  90437. result.addOptimization(new RenderTargetsOptimization(priority));
  90438. // Next priority
  90439. priority++;
  90440. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90441. return result;
  90442. };
  90443. return SceneOptimizerOptions;
  90444. }());
  90445. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90446. /**
  90447. * Class used to run optimizations in order to reach a target frame rate
  90448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90449. */
  90450. var SceneOptimizer = /** @class */ (function () {
  90451. /**
  90452. * Creates a new SceneOptimizer
  90453. * @param scene defines the scene to work on
  90454. * @param options defines the options to use with the SceneOptimizer
  90455. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90456. * @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)
  90457. */
  90458. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90459. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90460. if (improvementMode === void 0) { improvementMode = false; }
  90461. var _this = this;
  90462. this._isRunning = false;
  90463. this._currentPriorityLevel = 0;
  90464. this._targetFrameRate = 60;
  90465. this._trackerDuration = 2000;
  90466. this._currentFrameRate = 0;
  90467. this._improvementMode = false;
  90468. /**
  90469. * Defines an observable called when the optimizer reaches the target frame rate
  90470. */
  90471. this.onSuccessObservable = new BABYLON.Observable();
  90472. /**
  90473. * Defines an observable called when the optimizer enables an optimization
  90474. */
  90475. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90476. /**
  90477. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90478. */
  90479. this.onFailureObservable = new BABYLON.Observable();
  90480. if (!options) {
  90481. this._options = new SceneOptimizerOptions();
  90482. }
  90483. else {
  90484. this._options = options;
  90485. }
  90486. if (this._options.targetFrameRate) {
  90487. this._targetFrameRate = this._options.targetFrameRate;
  90488. }
  90489. if (this._options.trackerDuration) {
  90490. this._trackerDuration = this._options.trackerDuration;
  90491. }
  90492. if (autoGeneratePriorities) {
  90493. var priority = 0;
  90494. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90495. var optim = _a[_i];
  90496. optim.priority = priority++;
  90497. }
  90498. }
  90499. this._improvementMode = improvementMode;
  90500. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90501. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90502. _this._sceneDisposeObserver = null;
  90503. _this.dispose();
  90504. });
  90505. }
  90506. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90507. /**
  90508. * Gets a boolean indicating if the optimizer is in improvement mode
  90509. */
  90510. get: function () {
  90511. return this._improvementMode;
  90512. },
  90513. enumerable: true,
  90514. configurable: true
  90515. });
  90516. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90517. /**
  90518. * Gets the current priority level (0 at start)
  90519. */
  90520. get: function () {
  90521. return this._currentPriorityLevel;
  90522. },
  90523. enumerable: true,
  90524. configurable: true
  90525. });
  90526. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90527. /**
  90528. * Gets the current frame rate checked by the SceneOptimizer
  90529. */
  90530. get: function () {
  90531. return this._currentFrameRate;
  90532. },
  90533. enumerable: true,
  90534. configurable: true
  90535. });
  90536. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90537. /**
  90538. * Gets or sets the current target frame rate (60 by default)
  90539. */
  90540. get: function () {
  90541. return this._targetFrameRate;
  90542. },
  90543. /**
  90544. * Gets or sets the current target frame rate (60 by default)
  90545. */
  90546. set: function (value) {
  90547. this._targetFrameRate = value;
  90548. },
  90549. enumerable: true,
  90550. configurable: true
  90551. });
  90552. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90553. /**
  90554. * Gets or sets the current interval between two checks (every 2000ms by default)
  90555. */
  90556. get: function () {
  90557. return this._trackerDuration;
  90558. },
  90559. /**
  90560. * Gets or sets the current interval between two checks (every 2000ms by default)
  90561. */
  90562. set: function (value) {
  90563. this._trackerDuration = value;
  90564. },
  90565. enumerable: true,
  90566. configurable: true
  90567. });
  90568. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90569. /**
  90570. * Gets the list of active optimizations
  90571. */
  90572. get: function () {
  90573. return this._options.optimizations;
  90574. },
  90575. enumerable: true,
  90576. configurable: true
  90577. });
  90578. /**
  90579. * Stops the current optimizer
  90580. */
  90581. SceneOptimizer.prototype.stop = function () {
  90582. this._isRunning = false;
  90583. };
  90584. /**
  90585. * Reset the optimizer to initial step (current priority level = 0)
  90586. */
  90587. SceneOptimizer.prototype.reset = function () {
  90588. this._currentPriorityLevel = 0;
  90589. };
  90590. /**
  90591. * Start the optimizer. By default it will try to reach a specific framerate
  90592. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90593. */
  90594. SceneOptimizer.prototype.start = function () {
  90595. var _this = this;
  90596. if (this._isRunning) {
  90597. return;
  90598. }
  90599. this._isRunning = true;
  90600. // Let's wait for the scene to be ready before running our check
  90601. this._scene.executeWhenReady(function () {
  90602. setTimeout(function () {
  90603. _this._checkCurrentState();
  90604. }, _this._trackerDuration);
  90605. });
  90606. };
  90607. SceneOptimizer.prototype._checkCurrentState = function () {
  90608. var _this = this;
  90609. if (!this._isRunning) {
  90610. return;
  90611. }
  90612. var scene = this._scene;
  90613. var options = this._options;
  90614. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90615. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90616. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90617. this._isRunning = false;
  90618. this.onSuccessObservable.notifyObservers(this);
  90619. return;
  90620. }
  90621. // Apply current level of optimizations
  90622. var allDone = true;
  90623. var noOptimizationApplied = true;
  90624. for (var index = 0; index < options.optimizations.length; index++) {
  90625. var optimization = options.optimizations[index];
  90626. if (optimization.priority === this._currentPriorityLevel) {
  90627. noOptimizationApplied = false;
  90628. allDone = allDone && optimization.apply(scene, this);
  90629. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90630. }
  90631. }
  90632. // If no optimization was applied, this is a failure :(
  90633. if (noOptimizationApplied) {
  90634. this._isRunning = false;
  90635. this.onFailureObservable.notifyObservers(this);
  90636. return;
  90637. }
  90638. // If all optimizations were done, move to next level
  90639. if (allDone) {
  90640. this._currentPriorityLevel++;
  90641. }
  90642. // Let's the system running for a specific amount of time before checking FPS
  90643. scene.executeWhenReady(function () {
  90644. setTimeout(function () {
  90645. _this._checkCurrentState();
  90646. }, _this._trackerDuration);
  90647. });
  90648. };
  90649. /**
  90650. * Release all resources
  90651. */
  90652. SceneOptimizer.prototype.dispose = function () {
  90653. this.stop();
  90654. this.onSuccessObservable.clear();
  90655. this.onFailureObservable.clear();
  90656. this.onNewOptimizationAppliedObservable.clear();
  90657. if (this._sceneDisposeObserver) {
  90658. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90659. }
  90660. };
  90661. /**
  90662. * Helper function to create a SceneOptimizer with one single line of code
  90663. * @param scene defines the scene to work on
  90664. * @param options defines the options to use with the SceneOptimizer
  90665. * @param onSuccess defines a callback to call on success
  90666. * @param onFailure defines a callback to call on failure
  90667. * @returns the new SceneOptimizer object
  90668. */
  90669. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90670. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90671. if (onSuccess) {
  90672. optimizer.onSuccessObservable.add(function () {
  90673. onSuccess();
  90674. });
  90675. }
  90676. if (onFailure) {
  90677. optimizer.onFailureObservable.add(function () {
  90678. onFailure();
  90679. });
  90680. }
  90681. optimizer.start();
  90682. return optimizer;
  90683. };
  90684. return SceneOptimizer;
  90685. }());
  90686. BABYLON.SceneOptimizer = SceneOptimizer;
  90687. })(BABYLON || (BABYLON = {}));
  90688. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90689. var BABYLON;
  90690. (function (BABYLON) {
  90691. var OutlineRenderer = /** @class */ (function () {
  90692. function OutlineRenderer(scene) {
  90693. this.zOffset = 1;
  90694. this._scene = scene;
  90695. }
  90696. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90697. var _this = this;
  90698. if (useOverlay === void 0) { useOverlay = false; }
  90699. var scene = this._scene;
  90700. var engine = this._scene.getEngine();
  90701. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90702. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90703. return;
  90704. }
  90705. var mesh = subMesh.getRenderingMesh();
  90706. var material = subMesh.getMaterial();
  90707. if (!material || !scene.activeCamera) {
  90708. return;
  90709. }
  90710. engine.enableEffect(this._effect);
  90711. // Logarithmic depth
  90712. if (material.useLogarithmicDepth) {
  90713. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90714. }
  90715. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90716. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90717. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90718. // Bones
  90719. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90720. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90721. }
  90722. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90723. // Alpha test
  90724. if (material && material.needAlphaTesting()) {
  90725. var alphaTexture = material.getAlphaTestTexture();
  90726. if (alphaTexture) {
  90727. this._effect.setTexture("diffuseSampler", alphaTexture);
  90728. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90729. }
  90730. }
  90731. engine.setZOffset(-this.zOffset);
  90732. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90733. engine.setZOffset(0);
  90734. };
  90735. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90736. var defines = [];
  90737. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90738. var mesh = subMesh.getMesh();
  90739. var material = subMesh.getMaterial();
  90740. if (material) {
  90741. // Alpha test
  90742. if (material.needAlphaTesting()) {
  90743. defines.push("#define ALPHATEST");
  90744. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90745. attribs.push(BABYLON.VertexBuffer.UVKind);
  90746. defines.push("#define UV1");
  90747. }
  90748. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90749. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90750. defines.push("#define UV2");
  90751. }
  90752. }
  90753. //Logarithmic depth
  90754. if (material.useLogarithmicDepth) {
  90755. defines.push("#define LOGARITHMICDEPTH");
  90756. }
  90757. }
  90758. // Bones
  90759. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90760. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90761. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90762. if (mesh.numBoneInfluencers > 4) {
  90763. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90764. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90765. }
  90766. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90767. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90768. }
  90769. else {
  90770. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90771. }
  90772. // Instances
  90773. if (useInstances) {
  90774. defines.push("#define INSTANCES");
  90775. attribs.push("world0");
  90776. attribs.push("world1");
  90777. attribs.push("world2");
  90778. attribs.push("world3");
  90779. }
  90780. // Get correct effect
  90781. var join = defines.join("\n");
  90782. if (this._cachedDefines !== join) {
  90783. this._cachedDefines = join;
  90784. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90785. }
  90786. return this._effect.isReady();
  90787. };
  90788. return OutlineRenderer;
  90789. }());
  90790. BABYLON.OutlineRenderer = OutlineRenderer;
  90791. })(BABYLON || (BABYLON = {}));
  90792. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90793. var BABYLON;
  90794. (function (BABYLON) {
  90795. var FaceAdjacencies = /** @class */ (function () {
  90796. function FaceAdjacencies() {
  90797. this.edges = new Array();
  90798. this.edgesConnectedCount = 0;
  90799. }
  90800. return FaceAdjacencies;
  90801. }());
  90802. var EdgesRenderer = /** @class */ (function () {
  90803. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90804. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90805. if (epsilon === void 0) { epsilon = 0.95; }
  90806. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90807. this.edgesWidthScalerForOrthographic = 1000.0;
  90808. this.edgesWidthScalerForPerspective = 50.0;
  90809. this._linesPositions = new Array();
  90810. this._linesNormals = new Array();
  90811. this._linesIndices = new Array();
  90812. this._buffers = {};
  90813. this._checkVerticesInsteadOfIndices = false;
  90814. this._source = source;
  90815. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90816. this._epsilon = epsilon;
  90817. this._prepareRessources();
  90818. this._generateEdgesLines();
  90819. }
  90820. EdgesRenderer.prototype._prepareRessources = function () {
  90821. if (this._lineShader) {
  90822. return;
  90823. }
  90824. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90825. attributes: ["position", "normal"],
  90826. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90827. });
  90828. this._lineShader.disableDepthWrite = true;
  90829. this._lineShader.backFaceCulling = false;
  90830. };
  90831. EdgesRenderer.prototype._rebuild = function () {
  90832. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90833. if (buffer) {
  90834. buffer._rebuild();
  90835. }
  90836. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90837. if (buffer) {
  90838. buffer._rebuild();
  90839. }
  90840. var scene = this._source.getScene();
  90841. var engine = scene.getEngine();
  90842. this._ib = engine.createIndexBuffer(this._linesIndices);
  90843. };
  90844. EdgesRenderer.prototype.dispose = function () {
  90845. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90846. if (buffer) {
  90847. buffer.dispose();
  90848. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90849. }
  90850. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90851. if (buffer) {
  90852. buffer.dispose();
  90853. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90854. }
  90855. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90856. this._lineShader.dispose();
  90857. };
  90858. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90859. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90860. return 0;
  90861. }
  90862. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90863. return 1;
  90864. }
  90865. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90866. return 2;
  90867. }
  90868. return -1;
  90869. };
  90870. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90871. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90872. return 0;
  90873. }
  90874. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90875. return 1;
  90876. }
  90877. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90878. return 2;
  90879. }
  90880. return -1;
  90881. };
  90882. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90883. var needToCreateLine;
  90884. if (edge === undefined) {
  90885. needToCreateLine = true;
  90886. }
  90887. else {
  90888. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90889. needToCreateLine = dotProduct < this._epsilon;
  90890. }
  90891. if (needToCreateLine) {
  90892. var offset = this._linesPositions.length / 3;
  90893. var normal = p0.subtract(p1);
  90894. normal.normalize();
  90895. // Positions
  90896. this._linesPositions.push(p0.x);
  90897. this._linesPositions.push(p0.y);
  90898. this._linesPositions.push(p0.z);
  90899. this._linesPositions.push(p0.x);
  90900. this._linesPositions.push(p0.y);
  90901. this._linesPositions.push(p0.z);
  90902. this._linesPositions.push(p1.x);
  90903. this._linesPositions.push(p1.y);
  90904. this._linesPositions.push(p1.z);
  90905. this._linesPositions.push(p1.x);
  90906. this._linesPositions.push(p1.y);
  90907. this._linesPositions.push(p1.z);
  90908. // Normals
  90909. this._linesNormals.push(p1.x);
  90910. this._linesNormals.push(p1.y);
  90911. this._linesNormals.push(p1.z);
  90912. this._linesNormals.push(-1);
  90913. this._linesNormals.push(p1.x);
  90914. this._linesNormals.push(p1.y);
  90915. this._linesNormals.push(p1.z);
  90916. this._linesNormals.push(1);
  90917. this._linesNormals.push(p0.x);
  90918. this._linesNormals.push(p0.y);
  90919. this._linesNormals.push(p0.z);
  90920. this._linesNormals.push(-1);
  90921. this._linesNormals.push(p0.x);
  90922. this._linesNormals.push(p0.y);
  90923. this._linesNormals.push(p0.z);
  90924. this._linesNormals.push(1);
  90925. // Indices
  90926. this._linesIndices.push(offset);
  90927. this._linesIndices.push(offset + 1);
  90928. this._linesIndices.push(offset + 2);
  90929. this._linesIndices.push(offset);
  90930. this._linesIndices.push(offset + 2);
  90931. this._linesIndices.push(offset + 3);
  90932. }
  90933. };
  90934. EdgesRenderer.prototype._generateEdgesLines = function () {
  90935. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90936. var indices = this._source.getIndices();
  90937. if (!indices || !positions) {
  90938. return;
  90939. }
  90940. // First let's find adjacencies
  90941. var adjacencies = new Array();
  90942. var faceNormals = new Array();
  90943. var index;
  90944. var faceAdjacencies;
  90945. // Prepare faces
  90946. for (index = 0; index < indices.length; index += 3) {
  90947. faceAdjacencies = new FaceAdjacencies();
  90948. var p0Index = indices[index];
  90949. var p1Index = indices[index + 1];
  90950. var p2Index = indices[index + 2];
  90951. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  90952. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  90953. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  90954. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  90955. faceNormal.normalize();
  90956. faceNormals.push(faceNormal);
  90957. adjacencies.push(faceAdjacencies);
  90958. }
  90959. // Scan
  90960. for (index = 0; index < adjacencies.length; index++) {
  90961. faceAdjacencies = adjacencies[index];
  90962. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  90963. var otherFaceAdjacencies = adjacencies[otherIndex];
  90964. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  90965. break;
  90966. }
  90967. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  90968. continue;
  90969. }
  90970. var otherP0 = indices[otherIndex * 3];
  90971. var otherP1 = indices[otherIndex * 3 + 1];
  90972. var otherP2 = indices[otherIndex * 3 + 2];
  90973. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  90974. var otherEdgeIndex = 0;
  90975. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  90976. continue;
  90977. }
  90978. switch (edgeIndex) {
  90979. case 0:
  90980. if (this._checkVerticesInsteadOfIndices) {
  90981. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90982. }
  90983. else {
  90984. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  90985. }
  90986. break;
  90987. case 1:
  90988. if (this._checkVerticesInsteadOfIndices) {
  90989. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90990. }
  90991. else {
  90992. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  90993. }
  90994. break;
  90995. case 2:
  90996. if (this._checkVerticesInsteadOfIndices) {
  90997. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90998. }
  90999. else {
  91000. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91001. }
  91002. break;
  91003. }
  91004. if (otherEdgeIndex === -1) {
  91005. continue;
  91006. }
  91007. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91008. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91009. faceAdjacencies.edgesConnectedCount++;
  91010. otherFaceAdjacencies.edgesConnectedCount++;
  91011. if (faceAdjacencies.edgesConnectedCount === 3) {
  91012. break;
  91013. }
  91014. }
  91015. }
  91016. }
  91017. // Create lines
  91018. for (index = 0; index < adjacencies.length; index++) {
  91019. // 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
  91020. var current = adjacencies[index];
  91021. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91022. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91023. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91024. }
  91025. // Merge into a single mesh
  91026. var engine = this._source.getScene().getEngine();
  91027. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91028. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91029. this._ib = engine.createIndexBuffer(this._linesIndices);
  91030. this._indicesCount = this._linesIndices.length;
  91031. };
  91032. EdgesRenderer.prototype.render = function () {
  91033. var scene = this._source.getScene();
  91034. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91035. return;
  91036. }
  91037. var engine = scene.getEngine();
  91038. this._lineShader._preBind();
  91039. // VBOs
  91040. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91041. scene.resetCachedMaterial();
  91042. this._lineShader.setColor4("color", this._source.edgesColor);
  91043. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91044. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91045. }
  91046. else {
  91047. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91048. }
  91049. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91050. this._lineShader.bind(this._source.getWorldMatrix());
  91051. // Draw order
  91052. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91053. this._lineShader.unbind();
  91054. engine.setDepthWrite(true);
  91055. };
  91056. return EdgesRenderer;
  91057. }());
  91058. BABYLON.EdgesRenderer = EdgesRenderer;
  91059. })(BABYLON || (BABYLON = {}));
  91060. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91061. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91062. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91063. s = arguments[i];
  91064. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91065. t[p] = s[p];
  91066. }
  91067. return t;
  91068. };
  91069. var BABYLON;
  91070. (function (BABYLON) {
  91071. /**
  91072. * The effect layer Helps adding post process effect blended with the main pass.
  91073. *
  91074. * This can be for instance use to generate glow or higlight effects on the scene.
  91075. *
  91076. * The effect layer class can not be used directly and is intented to inherited from to be
  91077. * customized per effects.
  91078. */
  91079. var EffectLayer = /** @class */ (function () {
  91080. /**
  91081. * Instantiates a new effect Layer and references it in the scene.
  91082. * @param name The name of the layer
  91083. * @param scene The scene to use the layer in
  91084. */
  91085. function EffectLayer(
  91086. /** The Friendly of the effect in the scene */
  91087. name, scene) {
  91088. this._vertexBuffers = {};
  91089. this._maxSize = 0;
  91090. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91091. this._shouldRender = true;
  91092. this._postProcesses = [];
  91093. this._textures = [];
  91094. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91095. /**
  91096. * The clear color of the texture used to generate the glow map.
  91097. */
  91098. this.neutralColor = new BABYLON.Color4();
  91099. /**
  91100. * Specifies wether the highlight layer is enabled or not.
  91101. */
  91102. this.isEnabled = true;
  91103. /**
  91104. * An event triggered when the effect layer has been disposed.
  91105. */
  91106. this.onDisposeObservable = new BABYLON.Observable();
  91107. /**
  91108. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91109. */
  91110. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91111. /**
  91112. * An event triggered when the generated texture is being merged in the scene.
  91113. */
  91114. this.onBeforeComposeObservable = new BABYLON.Observable();
  91115. /**
  91116. * An event triggered when the generated texture has been merged in the scene.
  91117. */
  91118. this.onAfterComposeObservable = new BABYLON.Observable();
  91119. /**
  91120. * An event triggered when the efffect layer changes its size.
  91121. */
  91122. this.onSizeChangedObservable = new BABYLON.Observable();
  91123. this.name = name;
  91124. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91125. this._engine = scene.getEngine();
  91126. this._maxSize = this._engine.getCaps().maxTextureSize;
  91127. this._scene.effectLayers.push(this);
  91128. // Generate Buffers
  91129. this._generateIndexBuffer();
  91130. this._genrateVertexBuffer();
  91131. }
  91132. Object.defineProperty(EffectLayer.prototype, "camera", {
  91133. /**
  91134. * Gets the camera attached to the layer.
  91135. */
  91136. get: function () {
  91137. return this._effectLayerOptions.camera;
  91138. },
  91139. enumerable: true,
  91140. configurable: true
  91141. });
  91142. /**
  91143. * Initializes the effect layer with the required options.
  91144. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91145. */
  91146. EffectLayer.prototype._init = function (options) {
  91147. // Adapt options
  91148. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91149. this._setMainTextureSize();
  91150. this._createMainTexture();
  91151. this._createTextureAndPostProcesses();
  91152. this._mergeEffect = this._createMergeEffect();
  91153. };
  91154. /**
  91155. * Generates the index buffer of the full screen quad blending to the main canvas.
  91156. */
  91157. EffectLayer.prototype._generateIndexBuffer = function () {
  91158. // Indices
  91159. var indices = [];
  91160. indices.push(0);
  91161. indices.push(1);
  91162. indices.push(2);
  91163. indices.push(0);
  91164. indices.push(2);
  91165. indices.push(3);
  91166. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91167. };
  91168. /**
  91169. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91170. */
  91171. EffectLayer.prototype._genrateVertexBuffer = function () {
  91172. // VBO
  91173. var vertices = [];
  91174. vertices.push(1, 1);
  91175. vertices.push(-1, 1);
  91176. vertices.push(-1, -1);
  91177. vertices.push(1, -1);
  91178. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91179. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91180. };
  91181. /**
  91182. * Sets the main texture desired size which is the closest power of two
  91183. * of the engine canvas size.
  91184. */
  91185. EffectLayer.prototype._setMainTextureSize = function () {
  91186. if (this._effectLayerOptions.mainTextureFixedSize) {
  91187. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91188. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91189. }
  91190. else {
  91191. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91192. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91193. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91194. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91195. }
  91196. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91197. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91198. };
  91199. /**
  91200. * Creates the main texture for the effect layer.
  91201. */
  91202. EffectLayer.prototype._createMainTexture = function () {
  91203. var _this = this;
  91204. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91205. width: this._mainTextureDesiredSize.width,
  91206. height: this._mainTextureDesiredSize.height
  91207. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91208. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91209. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91210. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91211. this._mainTexture.anisotropicFilteringLevel = 1;
  91212. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91213. this._mainTexture.renderParticles = false;
  91214. this._mainTexture.renderList = null;
  91215. this._mainTexture.ignoreCameraViewport = true;
  91216. // Custom render function
  91217. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91218. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91219. var index;
  91220. var engine = _this._scene.getEngine();
  91221. if (depthOnlySubMeshes.length) {
  91222. engine.setColorWrite(false);
  91223. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91224. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91225. }
  91226. engine.setColorWrite(true);
  91227. }
  91228. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91229. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91230. }
  91231. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91232. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91233. }
  91234. for (index = 0; index < transparentSubMeshes.length; index++) {
  91235. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91236. }
  91237. };
  91238. this._mainTexture.onClearObservable.add(function (engine) {
  91239. engine.clear(_this.neutralColor, true, true, true);
  91240. });
  91241. };
  91242. /**
  91243. * Checks for the readiness of the element composing the layer.
  91244. * @param subMesh the mesh to check for
  91245. * @param useInstances specify wether or not to use instances to render the mesh
  91246. * @param emissiveTexture the associated emissive texture used to generate the glow
  91247. * @return true if ready otherwise, false
  91248. */
  91249. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91250. var material = subMesh.getMaterial();
  91251. if (!material) {
  91252. return false;
  91253. }
  91254. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91255. return false;
  91256. }
  91257. var defines = [];
  91258. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91259. var mesh = subMesh.getMesh();
  91260. var uv1 = false;
  91261. var uv2 = false;
  91262. // Alpha test
  91263. if (material && material.needAlphaTesting()) {
  91264. var alphaTexture = material.getAlphaTestTexture();
  91265. if (alphaTexture) {
  91266. defines.push("#define ALPHATEST");
  91267. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91268. alphaTexture.coordinatesIndex === 1) {
  91269. defines.push("#define DIFFUSEUV2");
  91270. uv2 = true;
  91271. }
  91272. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91273. defines.push("#define DIFFUSEUV1");
  91274. uv1 = true;
  91275. }
  91276. }
  91277. }
  91278. // Emissive
  91279. if (emissiveTexture) {
  91280. defines.push("#define EMISSIVE");
  91281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91282. emissiveTexture.coordinatesIndex === 1) {
  91283. defines.push("#define EMISSIVEUV2");
  91284. uv2 = true;
  91285. }
  91286. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91287. defines.push("#define EMISSIVEUV1");
  91288. uv1 = true;
  91289. }
  91290. }
  91291. if (uv1) {
  91292. attribs.push(BABYLON.VertexBuffer.UVKind);
  91293. defines.push("#define UV1");
  91294. }
  91295. if (uv2) {
  91296. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91297. defines.push("#define UV2");
  91298. }
  91299. // Bones
  91300. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91301. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91302. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91303. if (mesh.numBoneInfluencers > 4) {
  91304. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91305. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91306. }
  91307. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91308. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91309. }
  91310. else {
  91311. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91312. }
  91313. // Morph targets
  91314. var manager = mesh.morphTargetManager;
  91315. var morphInfluencers = 0;
  91316. if (manager) {
  91317. if (manager.numInfluencers > 0) {
  91318. defines.push("#define MORPHTARGETS");
  91319. morphInfluencers = manager.numInfluencers;
  91320. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91321. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91322. }
  91323. }
  91324. // Instances
  91325. if (useInstances) {
  91326. defines.push("#define INSTANCES");
  91327. attribs.push("world0");
  91328. attribs.push("world1");
  91329. attribs.push("world2");
  91330. attribs.push("world3");
  91331. }
  91332. // Get correct effect
  91333. var join = defines.join("\n");
  91334. if (this._cachedDefines !== join) {
  91335. this._cachedDefines = join;
  91336. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91337. }
  91338. return this._effectLayerMapGenerationEffect.isReady();
  91339. };
  91340. /**
  91341. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91342. */
  91343. EffectLayer.prototype.render = function () {
  91344. var currentEffect = this._mergeEffect;
  91345. // Check
  91346. if (!currentEffect.isReady())
  91347. return;
  91348. for (var i = 0; i < this._postProcesses.length; i++) {
  91349. if (!this._postProcesses[i].isReady()) {
  91350. return;
  91351. }
  91352. }
  91353. var engine = this._scene.getEngine();
  91354. this.onBeforeComposeObservable.notifyObservers(this);
  91355. // Render
  91356. engine.enableEffect(currentEffect);
  91357. engine.setState(false);
  91358. // VBOs
  91359. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91360. // Cache
  91361. var previousAlphaMode = engine.getAlphaMode();
  91362. // Go Blend.
  91363. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91364. // Blends the map on the main canvas.
  91365. this._internalRender(currentEffect);
  91366. // Restore Alpha
  91367. engine.setAlphaMode(previousAlphaMode);
  91368. this.onAfterComposeObservable.notifyObservers(this);
  91369. // Handle size changes.
  91370. var size = this._mainTexture.getSize();
  91371. this._setMainTextureSize();
  91372. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91373. // Recreate RTT and post processes on size change.
  91374. this.onSizeChangedObservable.notifyObservers(this);
  91375. this._disposeTextureAndPostProcesses();
  91376. this._createMainTexture();
  91377. this._createTextureAndPostProcesses();
  91378. }
  91379. };
  91380. /**
  91381. * Determine if a given mesh will be used in the current effect.
  91382. * @param mesh mesh to test
  91383. * @returns true if the mesh will be used
  91384. */
  91385. EffectLayer.prototype.hasMesh = function (mesh) {
  91386. return true;
  91387. };
  91388. /**
  91389. * Returns true if the layer contains information to display, otherwise false.
  91390. * @returns true if the glow layer should be rendered
  91391. */
  91392. EffectLayer.prototype.shouldRender = function () {
  91393. return this.isEnabled && this._shouldRender;
  91394. };
  91395. /**
  91396. * Returns true if the mesh should render, otherwise false.
  91397. * @param mesh The mesh to render
  91398. * @returns true if it should render otherwise false
  91399. */
  91400. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91401. return true;
  91402. };
  91403. /**
  91404. * Returns true if the mesh should render, otherwise false.
  91405. * @param mesh The mesh to render
  91406. * @returns true if it should render otherwise false
  91407. */
  91408. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91409. return true;
  91410. };
  91411. /**
  91412. * Renders the submesh passed in parameter to the generation map.
  91413. */
  91414. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91415. var _this = this;
  91416. if (!this.shouldRender()) {
  91417. return;
  91418. }
  91419. var material = subMesh.getMaterial();
  91420. var mesh = subMesh.getRenderingMesh();
  91421. var scene = this._scene;
  91422. var engine = scene.getEngine();
  91423. if (!material) {
  91424. return;
  91425. }
  91426. // Do not block in blend mode.
  91427. if (material.needAlphaBlendingForMesh(mesh)) {
  91428. return;
  91429. }
  91430. // Culling
  91431. engine.setState(material.backFaceCulling);
  91432. // Managing instances
  91433. var batch = mesh._getInstancesRenderList(subMesh._id);
  91434. if (batch.mustReturn) {
  91435. return;
  91436. }
  91437. // Early Exit per mesh
  91438. if (!this._shouldRenderMesh(mesh)) {
  91439. return;
  91440. }
  91441. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91442. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91443. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91444. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91445. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91446. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91447. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91448. // Alpha test
  91449. if (material && material.needAlphaTesting()) {
  91450. var alphaTexture = material.getAlphaTestTexture();
  91451. if (alphaTexture) {
  91452. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91453. var textureMatrix = alphaTexture.getTextureMatrix();
  91454. if (textureMatrix) {
  91455. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91456. }
  91457. }
  91458. }
  91459. // Glow emissive only
  91460. if (this._emissiveTextureAndColor.texture) {
  91461. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91462. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91463. }
  91464. // Bones
  91465. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91466. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91467. }
  91468. // Morph targets
  91469. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91470. // Draw
  91471. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91472. }
  91473. else {
  91474. // Need to reset refresh rate of the shadowMap
  91475. this._mainTexture.resetRefreshCounter();
  91476. }
  91477. };
  91478. /**
  91479. * Rebuild the required buffers.
  91480. * @hidden Internal use only.
  91481. */
  91482. EffectLayer.prototype._rebuild = function () {
  91483. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91484. if (vb) {
  91485. vb._rebuild();
  91486. }
  91487. this._generateIndexBuffer();
  91488. };
  91489. /**
  91490. * Dispose only the render target textures and post process.
  91491. */
  91492. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91493. this._mainTexture.dispose();
  91494. for (var i = 0; i < this._postProcesses.length; i++) {
  91495. if (this._postProcesses[i]) {
  91496. this._postProcesses[i].dispose();
  91497. }
  91498. }
  91499. this._postProcesses = [];
  91500. for (var i = 0; i < this._textures.length; i++) {
  91501. if (this._textures[i]) {
  91502. this._textures[i].dispose();
  91503. }
  91504. }
  91505. this._textures = [];
  91506. };
  91507. /**
  91508. * Dispose the highlight layer and free resources.
  91509. */
  91510. EffectLayer.prototype.dispose = function () {
  91511. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91512. if (vertexBuffer) {
  91513. vertexBuffer.dispose();
  91514. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91515. }
  91516. if (this._indexBuffer) {
  91517. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91518. this._indexBuffer = null;
  91519. }
  91520. // Clean textures and post processes
  91521. this._disposeTextureAndPostProcesses();
  91522. // Remove from scene
  91523. var index = this._scene.effectLayers.indexOf(this, 0);
  91524. if (index > -1) {
  91525. this._scene.effectLayers.splice(index, 1);
  91526. }
  91527. // Callback
  91528. this.onDisposeObservable.notifyObservers(this);
  91529. this.onDisposeObservable.clear();
  91530. this.onBeforeRenderMainTextureObservable.clear();
  91531. this.onBeforeComposeObservable.clear();
  91532. this.onAfterComposeObservable.clear();
  91533. this.onSizeChangedObservable.clear();
  91534. };
  91535. /**
  91536. * Gets the class name of the effect layer
  91537. * @returns the string with the class name of the effect layer
  91538. */
  91539. EffectLayer.prototype.getClassName = function () {
  91540. return "EffectLayer";
  91541. };
  91542. /**
  91543. * Creates an effect layer from parsed effect layer data
  91544. * @param parsedEffectLayer defines effect layer data
  91545. * @param scene defines the current scene
  91546. * @param rootUrl defines the root URL containing the effect layer information
  91547. * @returns a parsed effect Layer
  91548. */
  91549. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91550. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91551. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91552. };
  91553. __decorate([
  91554. BABYLON.serialize()
  91555. ], EffectLayer.prototype, "name", void 0);
  91556. __decorate([
  91557. BABYLON.serializeAsColor4()
  91558. ], EffectLayer.prototype, "neutralColor", void 0);
  91559. __decorate([
  91560. BABYLON.serialize()
  91561. ], EffectLayer.prototype, "isEnabled", void 0);
  91562. __decorate([
  91563. BABYLON.serializeAsCameraReference()
  91564. ], EffectLayer.prototype, "camera", null);
  91565. return EffectLayer;
  91566. }());
  91567. BABYLON.EffectLayer = EffectLayer;
  91568. })(BABYLON || (BABYLON = {}));
  91569. //# sourceMappingURL=babylon.effectLayer.js.map
  91570. var BABYLON;
  91571. (function (BABYLON) {
  91572. /**
  91573. * Special Glow Blur post process only blurring the alpha channel
  91574. * It enforces keeping the most luminous color in the color channel.
  91575. */
  91576. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91577. __extends(GlowBlurPostProcess, _super);
  91578. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91579. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91580. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91581. _this.direction = direction;
  91582. _this.kernel = kernel;
  91583. _this.onApplyObservable.add(function (effect) {
  91584. effect.setFloat2("screenSize", _this.width, _this.height);
  91585. effect.setVector2("direction", _this.direction);
  91586. effect.setFloat("blurWidth", _this.kernel);
  91587. });
  91588. return _this;
  91589. }
  91590. return GlowBlurPostProcess;
  91591. }(BABYLON.PostProcess));
  91592. /**
  91593. * The highlight layer Helps adding a glow effect around a mesh.
  91594. *
  91595. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91596. * glowy meshes to your scene.
  91597. *
  91598. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91599. */
  91600. var HighlightLayer = /** @class */ (function (_super) {
  91601. __extends(HighlightLayer, _super);
  91602. /**
  91603. * Instantiates a new highlight Layer and references it to the scene..
  91604. * @param name The name of the layer
  91605. * @param scene The scene to use the layer in
  91606. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91607. */
  91608. function HighlightLayer(name, scene, options) {
  91609. var _this = _super.call(this, name, scene) || this;
  91610. _this.name = name;
  91611. /**
  91612. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91613. */
  91614. _this.innerGlow = true;
  91615. /**
  91616. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91617. */
  91618. _this.outerGlow = true;
  91619. /**
  91620. * An event triggered when the highlight layer is being blurred.
  91621. */
  91622. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91623. /**
  91624. * An event triggered when the highlight layer has been blurred.
  91625. */
  91626. _this.onAfterBlurObservable = new BABYLON.Observable();
  91627. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91628. _this._meshes = {};
  91629. _this._excludedMeshes = {};
  91630. _this.neutralColor = HighlightLayer.NeutralColor;
  91631. // Warn on stencil
  91632. if (!_this._engine.isStencilEnable) {
  91633. 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 }");
  91634. }
  91635. // Adapt options
  91636. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91637. // Initialize the layer
  91638. _this._init({
  91639. alphaBlendingMode: _this._options.alphaBlendingMode,
  91640. camera: _this._options.camera,
  91641. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91642. mainTextureRatio: _this._options.mainTextureRatio
  91643. });
  91644. // Do not render as long as no meshes have been added
  91645. _this._shouldRender = false;
  91646. return _this;
  91647. }
  91648. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91649. /**
  91650. * Gets the horizontal size of the blur.
  91651. */
  91652. get: function () {
  91653. return this._horizontalBlurPostprocess.kernel;
  91654. },
  91655. /**
  91656. * Specifies the horizontal size of the blur.
  91657. */
  91658. set: function (value) {
  91659. this._horizontalBlurPostprocess.kernel = value;
  91660. },
  91661. enumerable: true,
  91662. configurable: true
  91663. });
  91664. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91665. /**
  91666. * Gets the vertical size of the blur.
  91667. */
  91668. get: function () {
  91669. return this._verticalBlurPostprocess.kernel;
  91670. },
  91671. /**
  91672. * Specifies the vertical size of the blur.
  91673. */
  91674. set: function (value) {
  91675. this._verticalBlurPostprocess.kernel = value;
  91676. },
  91677. enumerable: true,
  91678. configurable: true
  91679. });
  91680. /**
  91681. * Get the effect name of the layer.
  91682. * @return The effect name
  91683. */
  91684. HighlightLayer.prototype.getEffectName = function () {
  91685. return HighlightLayer.EffectName;
  91686. };
  91687. /**
  91688. * Create the merge effect. This is the shader use to blit the information back
  91689. * to the main canvas at the end of the scene rendering.
  91690. */
  91691. HighlightLayer.prototype._createMergeEffect = function () {
  91692. // Effect
  91693. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91694. };
  91695. /**
  91696. * Creates the render target textures and post processes used in the highlight layer.
  91697. */
  91698. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91699. var _this = this;
  91700. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91701. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91702. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91703. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91704. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91705. width: blurTextureWidth,
  91706. height: blurTextureHeight
  91707. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91708. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91709. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91710. this._blurTexture.anisotropicFilteringLevel = 16;
  91711. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91712. this._blurTexture.renderParticles = false;
  91713. this._blurTexture.ignoreCameraViewport = true;
  91714. this._textures = [this._blurTexture];
  91715. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91716. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91717. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91718. effect.setTexture("textureSampler", _this._mainTexture);
  91719. });
  91720. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91721. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91722. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91723. });
  91724. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91725. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91726. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91727. });
  91728. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91729. }
  91730. else {
  91731. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91732. width: blurTextureWidth,
  91733. height: blurTextureHeight
  91734. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91735. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91736. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91737. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91738. effect.setTexture("textureSampler", _this._mainTexture);
  91739. });
  91740. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91741. width: blurTextureWidth,
  91742. height: blurTextureHeight
  91743. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91744. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91745. }
  91746. this._mainTexture.onAfterUnbindObservable.add(function () {
  91747. _this.onBeforeBlurObservable.notifyObservers(_this);
  91748. var internalTexture = _this._blurTexture.getInternalTexture();
  91749. if (internalTexture) {
  91750. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91751. }
  91752. _this.onAfterBlurObservable.notifyObservers(_this);
  91753. });
  91754. // Prevent autoClear.
  91755. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91756. };
  91757. /**
  91758. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91759. */
  91760. HighlightLayer.prototype.needStencil = function () {
  91761. return true;
  91762. };
  91763. /**
  91764. * Checks for the readiness of the element composing the layer.
  91765. * @param subMesh the mesh to check for
  91766. * @param useInstances specify wether or not to use instances to render the mesh
  91767. * @param emissiveTexture the associated emissive texture used to generate the glow
  91768. * @return true if ready otherwise, false
  91769. */
  91770. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91771. var material = subMesh.getMaterial();
  91772. var mesh = subMesh.getRenderingMesh();
  91773. if (!material || !mesh || !this._meshes) {
  91774. return false;
  91775. }
  91776. var emissiveTexture = null;
  91777. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91778. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91779. emissiveTexture = material.emissiveTexture;
  91780. }
  91781. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91782. };
  91783. /**
  91784. * Implementation specific of rendering the generating effect on the main canvas.
  91785. * @param effect The effect used to render through
  91786. */
  91787. HighlightLayer.prototype._internalRender = function (effect) {
  91788. // Texture
  91789. effect.setTexture("textureSampler", this._blurTexture);
  91790. // Cache
  91791. var engine = this._engine;
  91792. var previousStencilBuffer = engine.getStencilBuffer();
  91793. var previousStencilFunction = engine.getStencilFunction();
  91794. var previousStencilMask = engine.getStencilMask();
  91795. var previousStencilOperationPass = engine.getStencilOperationPass();
  91796. var previousStencilOperationFail = engine.getStencilOperationFail();
  91797. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91798. var previousStencilReference = engine.getStencilFunctionReference();
  91799. // Stencil operations
  91800. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91801. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91802. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91803. // Draw order
  91804. engine.setStencilMask(0x00);
  91805. engine.setStencilBuffer(true);
  91806. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91807. // 2 passes inner outer
  91808. if (this.outerGlow) {
  91809. effect.setFloat("offset", 0);
  91810. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91812. }
  91813. if (this.innerGlow) {
  91814. effect.setFloat("offset", 1);
  91815. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91816. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91817. }
  91818. // Restore Cache
  91819. engine.setStencilFunction(previousStencilFunction);
  91820. engine.setStencilMask(previousStencilMask);
  91821. engine.setStencilBuffer(previousStencilBuffer);
  91822. engine.setStencilOperationPass(previousStencilOperationPass);
  91823. engine.setStencilOperationFail(previousStencilOperationFail);
  91824. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91825. engine.setStencilFunctionReference(previousStencilReference);
  91826. };
  91827. /**
  91828. * Returns true if the layer contains information to display, otherwise false.
  91829. */
  91830. HighlightLayer.prototype.shouldRender = function () {
  91831. if (_super.prototype.shouldRender.call(this)) {
  91832. return this._meshes ? true : false;
  91833. }
  91834. return false;
  91835. };
  91836. /**
  91837. * Returns true if the mesh should render, otherwise false.
  91838. * @param mesh The mesh to render
  91839. * @returns true if it should render otherwise false
  91840. */
  91841. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91842. // Excluded Mesh
  91843. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91844. return false;
  91845. }
  91846. ;
  91847. return true;
  91848. };
  91849. /**
  91850. * Sets the required values for both the emissive texture and and the main color.
  91851. */
  91852. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91853. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91854. if (highlightLayerMesh) {
  91855. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91856. }
  91857. else {
  91858. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91859. }
  91860. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91861. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91862. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91863. }
  91864. else {
  91865. this._emissiveTextureAndColor.texture = null;
  91866. }
  91867. };
  91868. /**
  91869. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91870. * @param mesh The mesh to exclude from the highlight layer
  91871. */
  91872. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91873. if (!this._excludedMeshes) {
  91874. return;
  91875. }
  91876. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91877. if (!meshExcluded) {
  91878. this._excludedMeshes[mesh.uniqueId] = {
  91879. mesh: mesh,
  91880. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91881. mesh.getEngine().setStencilBuffer(false);
  91882. }),
  91883. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91884. mesh.getEngine().setStencilBuffer(true);
  91885. }),
  91886. };
  91887. }
  91888. };
  91889. /**
  91890. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91891. * @param mesh The mesh to highlight
  91892. */
  91893. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91894. if (!this._excludedMeshes) {
  91895. return;
  91896. }
  91897. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91898. if (meshExcluded) {
  91899. if (meshExcluded.beforeRender) {
  91900. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91901. }
  91902. if (meshExcluded.afterRender) {
  91903. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91904. }
  91905. }
  91906. this._excludedMeshes[mesh.uniqueId] = null;
  91907. };
  91908. /**
  91909. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91910. * @param mesh mesh to test
  91911. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91912. */
  91913. HighlightLayer.prototype.hasMesh = function (mesh) {
  91914. if (!this._meshes) {
  91915. return false;
  91916. }
  91917. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91918. };
  91919. /**
  91920. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91921. * @param mesh The mesh to highlight
  91922. * @param color The color of the highlight
  91923. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91924. */
  91925. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91926. var _this = this;
  91927. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91928. if (!this._meshes) {
  91929. return;
  91930. }
  91931. var meshHighlight = this._meshes[mesh.uniqueId];
  91932. if (meshHighlight) {
  91933. meshHighlight.color = color;
  91934. }
  91935. else {
  91936. this._meshes[mesh.uniqueId] = {
  91937. mesh: mesh,
  91938. color: color,
  91939. // Lambda required for capture due to Observable this context
  91940. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  91941. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  91942. _this._defaultStencilReference(mesh);
  91943. }
  91944. else {
  91945. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  91946. }
  91947. }),
  91948. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  91949. glowEmissiveOnly: glowEmissiveOnly
  91950. };
  91951. }
  91952. this._shouldRender = true;
  91953. };
  91954. /**
  91955. * Remove a mesh from the highlight layer in order to make it stop glowing.
  91956. * @param mesh The mesh to highlight
  91957. */
  91958. HighlightLayer.prototype.removeMesh = function (mesh) {
  91959. if (!this._meshes) {
  91960. return;
  91961. }
  91962. var meshHighlight = this._meshes[mesh.uniqueId];
  91963. if (meshHighlight) {
  91964. if (meshHighlight.observerHighlight) {
  91965. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91966. }
  91967. if (meshHighlight.observerDefault) {
  91968. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91969. }
  91970. delete this._meshes[mesh.uniqueId];
  91971. }
  91972. this._shouldRender = false;
  91973. for (var meshHighlightToCheck in this._meshes) {
  91974. if (this._meshes[meshHighlightToCheck]) {
  91975. this._shouldRender = true;
  91976. break;
  91977. }
  91978. }
  91979. };
  91980. /**
  91981. * Force the stencil to the normal expected value for none glowing parts
  91982. */
  91983. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  91984. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  91985. };
  91986. /**
  91987. * Free any resources and references associated to a mesh.
  91988. * Internal use
  91989. * @param mesh The mesh to free.
  91990. */
  91991. HighlightLayer.prototype._disposeMesh = function (mesh) {
  91992. this.removeMesh(mesh);
  91993. this.removeExcludedMesh(mesh);
  91994. };
  91995. /**
  91996. * Dispose the highlight layer and free resources.
  91997. */
  91998. HighlightLayer.prototype.dispose = function () {
  91999. if (this._meshes) {
  92000. // Clean mesh references
  92001. for (var id in this._meshes) {
  92002. var meshHighlight = this._meshes[id];
  92003. if (meshHighlight && meshHighlight.mesh) {
  92004. if (meshHighlight.observerHighlight) {
  92005. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92006. }
  92007. if (meshHighlight.observerDefault) {
  92008. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92009. }
  92010. }
  92011. }
  92012. this._meshes = null;
  92013. }
  92014. if (this._excludedMeshes) {
  92015. for (var id in this._excludedMeshes) {
  92016. var meshHighlight = this._excludedMeshes[id];
  92017. if (meshHighlight) {
  92018. if (meshHighlight.beforeRender) {
  92019. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92020. }
  92021. if (meshHighlight.afterRender) {
  92022. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92023. }
  92024. }
  92025. }
  92026. this._excludedMeshes = null;
  92027. }
  92028. _super.prototype.dispose.call(this);
  92029. };
  92030. /**
  92031. * Gets the class name of the effect layer
  92032. * @returns the string with the class name of the effect layer
  92033. */
  92034. HighlightLayer.prototype.getClassName = function () {
  92035. return "HighlightLayer";
  92036. };
  92037. /**
  92038. * Serializes this Highlight layer
  92039. * @returns a serialized Highlight layer object
  92040. */
  92041. HighlightLayer.prototype.serialize = function () {
  92042. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92043. serializationObject.customType = "BABYLON.HighlightLayer";
  92044. // Highlighted meshes
  92045. serializationObject.meshes = [];
  92046. if (this._meshes) {
  92047. for (var m in this._meshes) {
  92048. var mesh = this._meshes[m];
  92049. if (mesh) {
  92050. serializationObject.meshes.push({
  92051. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92052. color: mesh.color.asArray(),
  92053. meshId: mesh.mesh.id
  92054. });
  92055. }
  92056. }
  92057. }
  92058. // Excluded meshes
  92059. serializationObject.excludedMeshes = [];
  92060. if (this._excludedMeshes) {
  92061. for (var e in this._excludedMeshes) {
  92062. var excludedMesh = this._excludedMeshes[e];
  92063. if (excludedMesh) {
  92064. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92065. }
  92066. }
  92067. }
  92068. return serializationObject;
  92069. };
  92070. /**
  92071. * Creates a Highlight layer from parsed Highlight layer data
  92072. * @param parsedHightlightLayer defines the Highlight layer data
  92073. * @param scene defines the current scene
  92074. * @param rootUrl defines the root URL containing the Highlight layer information
  92075. * @returns a parsed Highlight layer
  92076. */
  92077. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92078. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92079. var index;
  92080. // Excluded meshes
  92081. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92082. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92083. if (mesh) {
  92084. hl.addExcludedMesh(mesh);
  92085. }
  92086. }
  92087. // Included meshes
  92088. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92089. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92090. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92091. if (mesh) {
  92092. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92093. }
  92094. }
  92095. return hl;
  92096. };
  92097. /**
  92098. * Effect Name of the highlight layer.
  92099. */
  92100. HighlightLayer.EffectName = "HighlightLayer";
  92101. /**
  92102. * The neutral color used during the preparation of the glow effect.
  92103. * This is black by default as the blend operation is a blend operation.
  92104. */
  92105. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92106. /**
  92107. * Stencil value used for glowing meshes.
  92108. */
  92109. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92110. /**
  92111. * Stencil value used for the other meshes in the scene.
  92112. */
  92113. HighlightLayer.NormalMeshStencilReference = 0x01;
  92114. __decorate([
  92115. BABYLON.serialize()
  92116. ], HighlightLayer.prototype, "innerGlow", void 0);
  92117. __decorate([
  92118. BABYLON.serialize()
  92119. ], HighlightLayer.prototype, "outerGlow", void 0);
  92120. __decorate([
  92121. BABYLON.serialize()
  92122. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92123. __decorate([
  92124. BABYLON.serialize()
  92125. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92126. __decorate([
  92127. BABYLON.serialize("options")
  92128. ], HighlightLayer.prototype, "_options", void 0);
  92129. return HighlightLayer;
  92130. }(BABYLON.EffectLayer));
  92131. BABYLON.HighlightLayer = HighlightLayer;
  92132. })(BABYLON || (BABYLON = {}));
  92133. //# sourceMappingURL=babylon.highlightLayer.js.map
  92134. var BABYLON;
  92135. (function (BABYLON) {
  92136. /**
  92137. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92138. *
  92139. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92140. * glowy meshes to your scene.
  92141. *
  92142. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92143. */
  92144. var GlowLayer = /** @class */ (function (_super) {
  92145. __extends(GlowLayer, _super);
  92146. /**
  92147. * Instantiates a new glow Layer and references it to the scene.
  92148. * @param name The name of the layer
  92149. * @param scene The scene to use the layer in
  92150. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92151. */
  92152. function GlowLayer(name, scene, options) {
  92153. var _this = _super.call(this, name, scene) || this;
  92154. _this._intensity = 1.0;
  92155. _this._includedOnlyMeshes = [];
  92156. _this._excludedMeshes = [];
  92157. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92158. // Adapt options
  92159. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92160. // Initialize the layer
  92161. _this._init({
  92162. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92163. camera: _this._options.camera,
  92164. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92165. mainTextureRatio: _this._options.mainTextureRatio
  92166. });
  92167. return _this;
  92168. }
  92169. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92170. /**
  92171. * Gets the kernel size of the blur.
  92172. */
  92173. get: function () {
  92174. return this._horizontalBlurPostprocess1.kernel;
  92175. },
  92176. /**
  92177. * Sets the kernel size of the blur.
  92178. */
  92179. set: function (value) {
  92180. this._horizontalBlurPostprocess1.kernel = value;
  92181. this._verticalBlurPostprocess1.kernel = value;
  92182. this._horizontalBlurPostprocess2.kernel = value;
  92183. this._verticalBlurPostprocess2.kernel = value;
  92184. },
  92185. enumerable: true,
  92186. configurable: true
  92187. });
  92188. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92189. /**
  92190. * Gets the glow intensity.
  92191. */
  92192. get: function () {
  92193. return this._intensity;
  92194. },
  92195. /**
  92196. * Sets the glow intensity.
  92197. */
  92198. set: function (value) {
  92199. this._intensity = value;
  92200. },
  92201. enumerable: true,
  92202. configurable: true
  92203. });
  92204. /**
  92205. * Get the effect name of the layer.
  92206. * @return The effect name
  92207. */
  92208. GlowLayer.prototype.getEffectName = function () {
  92209. return GlowLayer.EffectName;
  92210. };
  92211. /**
  92212. * Create the merge effect. This is the shader use to blit the information back
  92213. * to the main canvas at the end of the scene rendering.
  92214. */
  92215. GlowLayer.prototype._createMergeEffect = function () {
  92216. // Effect
  92217. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92218. };
  92219. /**
  92220. * Creates the render target textures and post processes used in the glow layer.
  92221. */
  92222. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92223. var _this = this;
  92224. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92225. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92226. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92227. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92228. var textureType = 0;
  92229. if (this._engine.getCaps().textureHalfFloatRender) {
  92230. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92231. }
  92232. else {
  92233. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92234. }
  92235. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92236. width: blurTextureWidth,
  92237. height: blurTextureHeight
  92238. }, this._scene, false, true, textureType);
  92239. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92240. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92241. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92242. this._blurTexture1.renderParticles = false;
  92243. this._blurTexture1.ignoreCameraViewport = true;
  92244. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92245. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92246. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92247. width: blurTextureWidth2,
  92248. height: blurTextureHeight2
  92249. }, this._scene, false, true, textureType);
  92250. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92251. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92252. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92253. this._blurTexture2.renderParticles = false;
  92254. this._blurTexture2.ignoreCameraViewport = true;
  92255. this._textures = [this._blurTexture1, this._blurTexture2];
  92256. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92257. width: blurTextureWidth,
  92258. height: blurTextureHeight
  92259. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92260. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92261. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92262. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92263. effect.setTexture("textureSampler", _this._mainTexture);
  92264. });
  92265. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92266. width: blurTextureWidth,
  92267. height: blurTextureHeight
  92268. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92269. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92270. width: blurTextureWidth2,
  92271. height: blurTextureHeight2
  92272. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92273. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92274. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92275. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92276. effect.setTexture("textureSampler", _this._blurTexture1);
  92277. });
  92278. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92279. width: blurTextureWidth2,
  92280. height: blurTextureHeight2
  92281. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92282. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92283. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92284. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92285. this._mainTexture.samples = this._options.mainTextureSamples;
  92286. this._mainTexture.onAfterUnbindObservable.add(function () {
  92287. var internalTexture = _this._blurTexture1.getInternalTexture();
  92288. if (internalTexture) {
  92289. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92290. internalTexture = _this._blurTexture2.getInternalTexture();
  92291. if (internalTexture) {
  92292. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92293. }
  92294. }
  92295. });
  92296. // Prevent autoClear.
  92297. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92298. };
  92299. /**
  92300. * Checks for the readiness of the element composing the layer.
  92301. * @param subMesh the mesh to check for
  92302. * @param useInstances specify wether or not to use instances to render the mesh
  92303. * @param emissiveTexture the associated emissive texture used to generate the glow
  92304. * @return true if ready otherwise, false
  92305. */
  92306. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92307. var material = subMesh.getMaterial();
  92308. var mesh = subMesh.getRenderingMesh();
  92309. if (!material || !mesh) {
  92310. return false;
  92311. }
  92312. var emissiveTexture = material.emissiveTexture;
  92313. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92314. };
  92315. /**
  92316. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92317. */
  92318. GlowLayer.prototype.needStencil = function () {
  92319. return false;
  92320. };
  92321. /**
  92322. * Implementation specific of rendering the generating effect on the main canvas.
  92323. * @param effect The effect used to render through
  92324. */
  92325. GlowLayer.prototype._internalRender = function (effect) {
  92326. // Texture
  92327. effect.setTexture("textureSampler", this._blurTexture1);
  92328. effect.setTexture("textureSampler2", this._blurTexture2);
  92329. effect.setFloat("offset", this._intensity);
  92330. // Cache
  92331. var engine = this._engine;
  92332. var previousStencilBuffer = engine.getStencilBuffer();
  92333. // Draw order
  92334. engine.setStencilBuffer(false);
  92335. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92336. // Draw order
  92337. engine.setStencilBuffer(previousStencilBuffer);
  92338. };
  92339. /**
  92340. * Sets the required values for both the emissive texture and and the main color.
  92341. */
  92342. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92343. var textureLevel = 1.0;
  92344. if (this.customEmissiveTextureSelector) {
  92345. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92346. }
  92347. else {
  92348. if (material) {
  92349. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92350. if (this._emissiveTextureAndColor.texture) {
  92351. textureLevel = this._emissiveTextureAndColor.texture.level;
  92352. }
  92353. }
  92354. else {
  92355. this._emissiveTextureAndColor.texture = null;
  92356. }
  92357. }
  92358. if (this.customEmissiveColorSelector) {
  92359. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92360. }
  92361. else {
  92362. if (material.emissiveColor) {
  92363. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92364. }
  92365. else {
  92366. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92367. }
  92368. }
  92369. };
  92370. /**
  92371. * Returns true if the mesh should render, otherwise false.
  92372. * @param mesh The mesh to render
  92373. * @returns true if it should render otherwise false
  92374. */
  92375. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92376. return this.hasMesh(mesh);
  92377. };
  92378. /**
  92379. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92380. * @param mesh The mesh to exclude from the glow layer
  92381. */
  92382. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92383. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92384. this._excludedMeshes.push(mesh.uniqueId);
  92385. }
  92386. };
  92387. /**
  92388. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92389. * @param mesh The mesh to remove
  92390. */
  92391. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92392. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92393. if (index !== -1) {
  92394. this._excludedMeshes.splice(index, 1);
  92395. }
  92396. };
  92397. /**
  92398. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92399. * @param mesh The mesh to include in the glow layer
  92400. */
  92401. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92402. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92403. this._includedOnlyMeshes.push(mesh.uniqueId);
  92404. }
  92405. };
  92406. /**
  92407. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92408. * @param mesh The mesh to remove
  92409. */
  92410. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92411. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92412. if (index !== -1) {
  92413. this._includedOnlyMeshes.splice(index, 1);
  92414. }
  92415. };
  92416. /**
  92417. * Determine if a given mesh will be used in the glow layer
  92418. * @param mesh The mesh to test
  92419. * @returns true if the mesh will be highlighted by the current glow layer
  92420. */
  92421. GlowLayer.prototype.hasMesh = function (mesh) {
  92422. // Included Mesh
  92423. if (this._includedOnlyMeshes.length) {
  92424. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92425. }
  92426. ;
  92427. // Excluded Mesh
  92428. if (this._excludedMeshes.length) {
  92429. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92430. }
  92431. ;
  92432. return true;
  92433. };
  92434. /**
  92435. * Free any resources and references associated to a mesh.
  92436. * Internal use
  92437. * @param mesh The mesh to free.
  92438. */
  92439. GlowLayer.prototype._disposeMesh = function (mesh) {
  92440. this.removeIncludedOnlyMesh(mesh);
  92441. this.removeExcludedMesh(mesh);
  92442. };
  92443. /**
  92444. * Gets the class name of the effect layer
  92445. * @returns the string with the class name of the effect layer
  92446. */
  92447. GlowLayer.prototype.getClassName = function () {
  92448. return "GlowLayer";
  92449. };
  92450. /**
  92451. * Serializes this glow layer
  92452. * @returns a serialized glow layer object
  92453. */
  92454. GlowLayer.prototype.serialize = function () {
  92455. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92456. serializationObject.customType = "BABYLON.GlowLayer";
  92457. var index;
  92458. // Included meshes
  92459. serializationObject.includedMeshes = [];
  92460. if (this._includedOnlyMeshes.length) {
  92461. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92462. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92463. if (mesh) {
  92464. serializationObject.includedMeshes.push(mesh.id);
  92465. }
  92466. }
  92467. }
  92468. // Excluded meshes
  92469. serializationObject.excludedMeshes = [];
  92470. if (this._excludedMeshes.length) {
  92471. for (index = 0; index < this._excludedMeshes.length; index++) {
  92472. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92473. if (mesh) {
  92474. serializationObject.excludedMeshes.push(mesh.id);
  92475. }
  92476. }
  92477. }
  92478. return serializationObject;
  92479. };
  92480. /**
  92481. * Creates a Glow Layer from parsed glow layer data
  92482. * @param parsedGlowLayer defines glow layer data
  92483. * @param scene defines the current scene
  92484. * @param rootUrl defines the root URL containing the glow layer information
  92485. * @returns a parsed Glow Layer
  92486. */
  92487. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92488. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92489. var index;
  92490. // Excluded meshes
  92491. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92492. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92493. if (mesh) {
  92494. gl.addExcludedMesh(mesh);
  92495. }
  92496. }
  92497. // Included meshes
  92498. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92499. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92500. if (mesh) {
  92501. gl.addIncludedOnlyMesh(mesh);
  92502. }
  92503. }
  92504. return gl;
  92505. };
  92506. /**
  92507. * Effect Name of the layer.
  92508. */
  92509. GlowLayer.EffectName = "GlowLayer";
  92510. /**
  92511. * The default blur kernel size used for the glow.
  92512. */
  92513. GlowLayer.DefaultBlurKernelSize = 32;
  92514. /**
  92515. * The default texture size ratio used for the glow.
  92516. */
  92517. GlowLayer.DefaultTextureRatio = 0.5;
  92518. __decorate([
  92519. BABYLON.serialize()
  92520. ], GlowLayer.prototype, "blurKernelSize", null);
  92521. __decorate([
  92522. BABYLON.serialize()
  92523. ], GlowLayer.prototype, "intensity", null);
  92524. __decorate([
  92525. BABYLON.serialize("options")
  92526. ], GlowLayer.prototype, "_options", void 0);
  92527. return GlowLayer;
  92528. }(BABYLON.EffectLayer));
  92529. BABYLON.GlowLayer = GlowLayer;
  92530. })(BABYLON || (BABYLON = {}));
  92531. //# sourceMappingURL=babylon.glowLayer.js.map
  92532. var BABYLON;
  92533. (function (BABYLON) {
  92534. /**
  92535. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92536. */
  92537. var AssetTaskState;
  92538. (function (AssetTaskState) {
  92539. /**
  92540. * Initialization
  92541. */
  92542. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92543. /**
  92544. * Running
  92545. */
  92546. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92547. /**
  92548. * Done
  92549. */
  92550. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92551. /**
  92552. * Error
  92553. */
  92554. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92555. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92556. /**
  92557. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92558. */
  92559. var AbstractAssetTask = /** @class */ (function () {
  92560. /**
  92561. * Creates a new {BABYLON.AssetsManager}
  92562. * @param name defines the name of the task
  92563. */
  92564. function AbstractAssetTask(
  92565. /**
  92566. * Task name
  92567. */ name) {
  92568. this.name = name;
  92569. this._isCompleted = false;
  92570. this._taskState = AssetTaskState.INIT;
  92571. }
  92572. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92573. /**
  92574. * Get if the task is completed
  92575. */
  92576. get: function () {
  92577. return this._isCompleted;
  92578. },
  92579. enumerable: true,
  92580. configurable: true
  92581. });
  92582. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92583. /**
  92584. * Gets the current state of the task
  92585. */
  92586. get: function () {
  92587. return this._taskState;
  92588. },
  92589. enumerable: true,
  92590. configurable: true
  92591. });
  92592. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92593. /**
  92594. * Gets the current error object (if task is in error)
  92595. */
  92596. get: function () {
  92597. return this._errorObject;
  92598. },
  92599. enumerable: true,
  92600. configurable: true
  92601. });
  92602. /**
  92603. * Internal only
  92604. * @hidden
  92605. */
  92606. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92607. if (this._errorObject) {
  92608. return;
  92609. }
  92610. this._errorObject = {
  92611. message: message,
  92612. exception: exception
  92613. };
  92614. };
  92615. /**
  92616. * Execute the current task
  92617. * @param scene defines the scene where you want your assets to be loaded
  92618. * @param onSuccess is a callback called when the task is successfully executed
  92619. * @param onError is a callback called if an error occurs
  92620. */
  92621. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92622. var _this = this;
  92623. this._taskState = AssetTaskState.RUNNING;
  92624. this.runTask(scene, function () {
  92625. _this.onDoneCallback(onSuccess, onError);
  92626. }, function (msg, exception) {
  92627. _this.onErrorCallback(onError, msg, exception);
  92628. });
  92629. };
  92630. /**
  92631. * Execute the current task
  92632. * @param scene defines the scene where you want your assets to be loaded
  92633. * @param onSuccess is a callback called when the task is successfully executed
  92634. * @param onError is a callback called if an error occurs
  92635. */
  92636. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92637. throw new Error("runTask is not implemented");
  92638. };
  92639. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92640. this._taskState = AssetTaskState.ERROR;
  92641. this._errorObject = {
  92642. message: message,
  92643. exception: exception
  92644. };
  92645. if (this.onError) {
  92646. this.onError(this, message, exception);
  92647. }
  92648. onError();
  92649. };
  92650. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92651. try {
  92652. this._taskState = AssetTaskState.DONE;
  92653. this._isCompleted = true;
  92654. if (this.onSuccess) {
  92655. this.onSuccess(this);
  92656. }
  92657. onSuccess();
  92658. }
  92659. catch (e) {
  92660. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92661. }
  92662. };
  92663. return AbstractAssetTask;
  92664. }());
  92665. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92666. /**
  92667. * Class used to share progress information about assets loading
  92668. */
  92669. var AssetsProgressEvent = /** @class */ (function () {
  92670. /**
  92671. * Creates a {BABYLON.AssetsProgressEvent}
  92672. * @param remainingCount defines the number of remaining tasks to process
  92673. * @param totalCount defines the total number of tasks
  92674. * @param task defines the task that was just processed
  92675. */
  92676. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92677. this.remainingCount = remainingCount;
  92678. this.totalCount = totalCount;
  92679. this.task = task;
  92680. }
  92681. return AssetsProgressEvent;
  92682. }());
  92683. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92684. /**
  92685. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92686. */
  92687. var MeshAssetTask = /** @class */ (function (_super) {
  92688. __extends(MeshAssetTask, _super);
  92689. /**
  92690. * Creates a new {BABYLON.MeshAssetTask}
  92691. * @param name defines the name of the task
  92692. * @param meshesNames defines the list of mesh's names you want to load
  92693. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92694. * @param sceneFilename defines the filename of the scene to load from
  92695. */
  92696. function MeshAssetTask(
  92697. /**
  92698. * Defines the name of the task
  92699. */
  92700. name,
  92701. /**
  92702. * Defines the list of mesh's names you want to load
  92703. */
  92704. meshesNames,
  92705. /**
  92706. * Defines the root url to use as a base to load your meshes and associated resources
  92707. */
  92708. rootUrl,
  92709. /**
  92710. * Defines the filename of the scene to load from
  92711. */
  92712. sceneFilename) {
  92713. var _this = _super.call(this, name) || this;
  92714. _this.name = name;
  92715. _this.meshesNames = meshesNames;
  92716. _this.rootUrl = rootUrl;
  92717. _this.sceneFilename = sceneFilename;
  92718. return _this;
  92719. }
  92720. /**
  92721. * Execute the current task
  92722. * @param scene defines the scene where you want your assets to be loaded
  92723. * @param onSuccess is a callback called when the task is successfully executed
  92724. * @param onError is a callback called if an error occurs
  92725. */
  92726. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92727. var _this = this;
  92728. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92729. _this.loadedMeshes = meshes;
  92730. _this.loadedParticleSystems = particleSystems;
  92731. _this.loadedSkeletons = skeletons;
  92732. onSuccess();
  92733. }, null, function (scene, message, exception) {
  92734. onError(message, exception);
  92735. });
  92736. };
  92737. return MeshAssetTask;
  92738. }(AbstractAssetTask));
  92739. BABYLON.MeshAssetTask = MeshAssetTask;
  92740. /**
  92741. * Define a task used by {BABYLON.AssetsManager} to load text content
  92742. */
  92743. var TextFileAssetTask = /** @class */ (function (_super) {
  92744. __extends(TextFileAssetTask, _super);
  92745. /**
  92746. * Creates a new TextFileAssetTask object
  92747. * @param name defines the name of the task
  92748. * @param url defines the location of the file to load
  92749. */
  92750. function TextFileAssetTask(
  92751. /**
  92752. * Defines the name of the task
  92753. */
  92754. name,
  92755. /**
  92756. * Defines the location of the file to load
  92757. */
  92758. url) {
  92759. var _this = _super.call(this, name) || this;
  92760. _this.name = name;
  92761. _this.url = url;
  92762. return _this;
  92763. }
  92764. /**
  92765. * Execute the current task
  92766. * @param scene defines the scene where you want your assets to be loaded
  92767. * @param onSuccess is a callback called when the task is successfully executed
  92768. * @param onError is a callback called if an error occurs
  92769. */
  92770. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92771. var _this = this;
  92772. scene._loadFile(this.url, function (data) {
  92773. _this.text = data;
  92774. onSuccess();
  92775. }, undefined, false, false, function (request, exception) {
  92776. if (request) {
  92777. onError(request.status + " " + request.statusText, exception);
  92778. }
  92779. });
  92780. };
  92781. return TextFileAssetTask;
  92782. }(AbstractAssetTask));
  92783. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92784. /**
  92785. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92786. */
  92787. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92788. __extends(BinaryFileAssetTask, _super);
  92789. /**
  92790. * Creates a new BinaryFileAssetTask object
  92791. * @param name defines the name of the new task
  92792. * @param url defines the location of the file to load
  92793. */
  92794. function BinaryFileAssetTask(
  92795. /**
  92796. * Defines the name of the task
  92797. */
  92798. name,
  92799. /**
  92800. * Defines the location of the file to load
  92801. */
  92802. url) {
  92803. var _this = _super.call(this, name) || this;
  92804. _this.name = name;
  92805. _this.url = url;
  92806. return _this;
  92807. }
  92808. /**
  92809. * Execute the current task
  92810. * @param scene defines the scene where you want your assets to be loaded
  92811. * @param onSuccess is a callback called when the task is successfully executed
  92812. * @param onError is a callback called if an error occurs
  92813. */
  92814. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92815. var _this = this;
  92816. scene._loadFile(this.url, function (data) {
  92817. _this.data = data;
  92818. onSuccess();
  92819. }, undefined, true, true, function (request, exception) {
  92820. if (request) {
  92821. onError(request.status + " " + request.statusText, exception);
  92822. }
  92823. });
  92824. };
  92825. return BinaryFileAssetTask;
  92826. }(AbstractAssetTask));
  92827. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92828. /**
  92829. * Define a task used by {BABYLON.AssetsManager} to load images
  92830. */
  92831. var ImageAssetTask = /** @class */ (function (_super) {
  92832. __extends(ImageAssetTask, _super);
  92833. /**
  92834. * Creates a new ImageAssetTask
  92835. * @param name defines the name of the task
  92836. * @param url defines the location of the image to load
  92837. */
  92838. function ImageAssetTask(
  92839. /**
  92840. * Defines the name of the task
  92841. */
  92842. name,
  92843. /**
  92844. * Defines the location of the image to load
  92845. */
  92846. url) {
  92847. var _this = _super.call(this, name) || this;
  92848. _this.name = name;
  92849. _this.url = url;
  92850. return _this;
  92851. }
  92852. /**
  92853. * Execute the current task
  92854. * @param scene defines the scene where you want your assets to be loaded
  92855. * @param onSuccess is a callback called when the task is successfully executed
  92856. * @param onError is a callback called if an error occurs
  92857. */
  92858. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92859. var _this = this;
  92860. var img = new Image();
  92861. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92862. img.onload = function () {
  92863. _this.image = img;
  92864. onSuccess();
  92865. };
  92866. img.onerror = function (err) {
  92867. onError("Error loading image", err);
  92868. };
  92869. img.src = this.url;
  92870. };
  92871. return ImageAssetTask;
  92872. }(AbstractAssetTask));
  92873. BABYLON.ImageAssetTask = ImageAssetTask;
  92874. /**
  92875. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92876. */
  92877. var TextureAssetTask = /** @class */ (function (_super) {
  92878. __extends(TextureAssetTask, _super);
  92879. /**
  92880. * Creates a new TextureAssetTask object
  92881. * @param name defines the name of the task
  92882. * @param url defines the location of the file to load
  92883. * @param noMipmap defines if mipmap should not be generated (default is false)
  92884. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92885. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92886. */
  92887. function TextureAssetTask(
  92888. /**
  92889. * Defines the name of the task
  92890. */
  92891. name,
  92892. /**
  92893. * Defines the location of the file to load
  92894. */
  92895. url,
  92896. /**
  92897. * Defines if mipmap should not be generated (default is false)
  92898. */
  92899. noMipmap,
  92900. /**
  92901. * Defines if texture must be inverted on Y axis (default is false)
  92902. */
  92903. invertY,
  92904. /**
  92905. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92906. */
  92907. samplingMode) {
  92908. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92909. var _this = _super.call(this, name) || this;
  92910. _this.name = name;
  92911. _this.url = url;
  92912. _this.noMipmap = noMipmap;
  92913. _this.invertY = invertY;
  92914. _this.samplingMode = samplingMode;
  92915. return _this;
  92916. }
  92917. /**
  92918. * Execute the current task
  92919. * @param scene defines the scene where you want your assets to be loaded
  92920. * @param onSuccess is a callback called when the task is successfully executed
  92921. * @param onError is a callback called if an error occurs
  92922. */
  92923. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92924. var onload = function () {
  92925. onSuccess();
  92926. };
  92927. var onerror = function (message, exception) {
  92928. onError(message, exception);
  92929. };
  92930. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92931. };
  92932. return TextureAssetTask;
  92933. }(AbstractAssetTask));
  92934. BABYLON.TextureAssetTask = TextureAssetTask;
  92935. /**
  92936. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92937. */
  92938. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92939. __extends(CubeTextureAssetTask, _super);
  92940. /**
  92941. * Creates a new CubeTextureAssetTask
  92942. * @param name defines the name of the task
  92943. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92944. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92945. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92946. * @param files defines the explicit list of files (undefined by default)
  92947. */
  92948. function CubeTextureAssetTask(
  92949. /**
  92950. * Defines the name of the task
  92951. */
  92952. name,
  92953. /**
  92954. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92955. */
  92956. url,
  92957. /**
  92958. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92959. */
  92960. extensions,
  92961. /**
  92962. * Defines if mipmaps should not be generated (default is false)
  92963. */
  92964. noMipmap,
  92965. /**
  92966. * Defines the explicit list of files (undefined by default)
  92967. */
  92968. files) {
  92969. var _this = _super.call(this, name) || this;
  92970. _this.name = name;
  92971. _this.url = url;
  92972. _this.extensions = extensions;
  92973. _this.noMipmap = noMipmap;
  92974. _this.files = files;
  92975. return _this;
  92976. }
  92977. /**
  92978. * Execute the current task
  92979. * @param scene defines the scene where you want your assets to be loaded
  92980. * @param onSuccess is a callback called when the task is successfully executed
  92981. * @param onError is a callback called if an error occurs
  92982. */
  92983. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92984. var onload = function () {
  92985. onSuccess();
  92986. };
  92987. var onerror = function (message, exception) {
  92988. onError(message, exception);
  92989. };
  92990. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  92991. };
  92992. return CubeTextureAssetTask;
  92993. }(AbstractAssetTask));
  92994. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  92995. /**
  92996. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  92997. */
  92998. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  92999. __extends(HDRCubeTextureAssetTask, _super);
  93000. /**
  93001. * Creates a new HDRCubeTextureAssetTask object
  93002. * @param name defines the name of the task
  93003. * @param url defines the location of the file to load
  93004. * @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.
  93005. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93006. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93007. * @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)
  93008. * @param reserved Internal use only
  93009. */
  93010. function HDRCubeTextureAssetTask(
  93011. /**
  93012. * Defines the name of the task
  93013. */
  93014. name,
  93015. /**
  93016. * Defines the location of the file to load
  93017. */
  93018. url,
  93019. /**
  93020. * Defines the desired size (the more it increases the longer the generation will be)
  93021. */
  93022. size,
  93023. /**
  93024. * Defines if mipmaps should not be generated (default is false)
  93025. */
  93026. noMipmap,
  93027. /**
  93028. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93029. */
  93030. generateHarmonics,
  93031. /**
  93032. * 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)
  93033. */
  93034. gammaSpace,
  93035. /**
  93036. * Internal Use Only
  93037. */
  93038. reserved) {
  93039. if (noMipmap === void 0) { noMipmap = false; }
  93040. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93041. if (gammaSpace === void 0) { gammaSpace = false; }
  93042. if (reserved === void 0) { reserved = false; }
  93043. var _this = _super.call(this, name) || this;
  93044. _this.name = name;
  93045. _this.url = url;
  93046. _this.size = size;
  93047. _this.noMipmap = noMipmap;
  93048. _this.generateHarmonics = generateHarmonics;
  93049. _this.gammaSpace = gammaSpace;
  93050. _this.reserved = reserved;
  93051. return _this;
  93052. }
  93053. /**
  93054. * Execute the current task
  93055. * @param scene defines the scene where you want your assets to be loaded
  93056. * @param onSuccess is a callback called when the task is successfully executed
  93057. * @param onError is a callback called if an error occurs
  93058. */
  93059. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93060. var onload = function () {
  93061. onSuccess();
  93062. };
  93063. var onerror = function (message, exception) {
  93064. onError(message, exception);
  93065. };
  93066. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93067. };
  93068. return HDRCubeTextureAssetTask;
  93069. }(AbstractAssetTask));
  93070. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93071. /**
  93072. * This class can be used to easily import assets into a scene
  93073. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93074. */
  93075. var AssetsManager = /** @class */ (function () {
  93076. /**
  93077. * Creates a new AssetsManager
  93078. * @param scene defines the scene to work on
  93079. */
  93080. function AssetsManager(scene) {
  93081. this._isLoading = false;
  93082. this._tasks = new Array();
  93083. this._waitingTasksCount = 0;
  93084. this._totalTasksCount = 0;
  93085. /**
  93086. * Observable called when all tasks are processed
  93087. */
  93088. this.onTaskSuccessObservable = new BABYLON.Observable();
  93089. /**
  93090. * Observable called when a task had an error
  93091. */
  93092. this.onTaskErrorObservable = new BABYLON.Observable();
  93093. /**
  93094. * Observable called when a task is successful
  93095. */
  93096. this.onTasksDoneObservable = new BABYLON.Observable();
  93097. /**
  93098. * Observable called when a task is done (whatever the result is)
  93099. */
  93100. this.onProgressObservable = new BABYLON.Observable();
  93101. /**
  93102. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93103. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93104. */
  93105. this.useDefaultLoadingScreen = true;
  93106. this._scene = scene;
  93107. }
  93108. /**
  93109. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93110. * @param taskName defines the name of the new task
  93111. * @param meshesNames defines the name of meshes to load
  93112. * @param rootUrl defines the root url to use to locate files
  93113. * @param sceneFilename defines the filename of the scene file
  93114. * @returns a new {BABYLON.MeshAssetTask} object
  93115. */
  93116. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93117. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93118. this._tasks.push(task);
  93119. return task;
  93120. };
  93121. /**
  93122. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93123. * @param taskName defines the name of the new task
  93124. * @param url defines the url of the file to load
  93125. * @returns a new {BABYLON.TextFileAssetTask} object
  93126. */
  93127. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93128. var task = new TextFileAssetTask(taskName, url);
  93129. this._tasks.push(task);
  93130. return task;
  93131. };
  93132. /**
  93133. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93134. * @param taskName defines the name of the new task
  93135. * @param url defines the url of the file to load
  93136. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93137. */
  93138. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93139. var task = new BinaryFileAssetTask(taskName, url);
  93140. this._tasks.push(task);
  93141. return task;
  93142. };
  93143. /**
  93144. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93145. * @param taskName defines the name of the new task
  93146. * @param url defines the url of the file to load
  93147. * @returns a new {BABYLON.ImageAssetTask} object
  93148. */
  93149. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93150. var task = new ImageAssetTask(taskName, url);
  93151. this._tasks.push(task);
  93152. return task;
  93153. };
  93154. /**
  93155. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93156. * @param taskName defines the name of the new task
  93157. * @param url defines the url of the file to load
  93158. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93159. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93160. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93161. * @returns a new {BABYLON.TextureAssetTask} object
  93162. */
  93163. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93164. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93165. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93166. this._tasks.push(task);
  93167. return task;
  93168. };
  93169. /**
  93170. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93171. * @param taskName defines the name of the new task
  93172. * @param url defines the url of the file to load
  93173. * @param extensions defines the extension to use to load the cube map (can be null)
  93174. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93175. * @param files defines the list of files to load (can be null)
  93176. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93177. */
  93178. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93179. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93180. this._tasks.push(task);
  93181. return task;
  93182. };
  93183. /**
  93184. *
  93185. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93186. * @param taskName defines the name of the new task
  93187. * @param url defines the url of the file to load
  93188. * @param size defines the size you want for the cubemap (can be null)
  93189. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93190. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93191. * @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)
  93192. * @param reserved Internal use only
  93193. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93194. */
  93195. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93196. if (noMipmap === void 0) { noMipmap = false; }
  93197. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93198. if (gammaSpace === void 0) { gammaSpace = false; }
  93199. if (reserved === void 0) { reserved = false; }
  93200. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93201. this._tasks.push(task);
  93202. return task;
  93203. };
  93204. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93205. var _this = this;
  93206. this._waitingTasksCount--;
  93207. try {
  93208. if (task.taskState === AssetTaskState.DONE) {
  93209. // Let's remove successfull tasks
  93210. BABYLON.Tools.SetImmediate(function () {
  93211. var index = _this._tasks.indexOf(task);
  93212. if (index > -1) {
  93213. _this._tasks.splice(index, 1);
  93214. }
  93215. });
  93216. }
  93217. if (this.onProgress) {
  93218. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93219. }
  93220. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93221. }
  93222. catch (e) {
  93223. BABYLON.Tools.Error("Error running progress callbacks.");
  93224. console.log(e);
  93225. }
  93226. if (this._waitingTasksCount === 0) {
  93227. try {
  93228. if (this.onFinish) {
  93229. this.onFinish(this._tasks);
  93230. }
  93231. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93232. }
  93233. catch (e) {
  93234. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93235. console.log(e);
  93236. }
  93237. this._isLoading = false;
  93238. this._scene.getEngine().hideLoadingUI();
  93239. }
  93240. };
  93241. AssetsManager.prototype._runTask = function (task) {
  93242. var _this = this;
  93243. var done = function () {
  93244. try {
  93245. if (_this.onTaskSuccess) {
  93246. _this.onTaskSuccess(task);
  93247. }
  93248. _this.onTaskSuccessObservable.notifyObservers(task);
  93249. _this._decreaseWaitingTasksCount(task);
  93250. }
  93251. catch (e) {
  93252. error("Error executing task success callbacks", e);
  93253. }
  93254. };
  93255. var error = function (message, exception) {
  93256. task._setErrorObject(message, exception);
  93257. if (_this.onTaskError) {
  93258. _this.onTaskError(task);
  93259. }
  93260. _this.onTaskErrorObservable.notifyObservers(task);
  93261. _this._decreaseWaitingTasksCount(task);
  93262. };
  93263. task.run(this._scene, done, error);
  93264. };
  93265. /**
  93266. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93267. * @return the current instance of the {BABYLON.AssetsManager}
  93268. */
  93269. AssetsManager.prototype.reset = function () {
  93270. this._isLoading = false;
  93271. this._tasks = new Array();
  93272. return this;
  93273. };
  93274. /**
  93275. * Start the loading process
  93276. * @return the current instance of the {BABYLON.AssetsManager}
  93277. */
  93278. AssetsManager.prototype.load = function () {
  93279. if (this._isLoading) {
  93280. return this;
  93281. }
  93282. this._isLoading = true;
  93283. this._waitingTasksCount = this._tasks.length;
  93284. this._totalTasksCount = this._tasks.length;
  93285. if (this._waitingTasksCount === 0) {
  93286. this._isLoading = false;
  93287. if (this.onFinish) {
  93288. this.onFinish(this._tasks);
  93289. }
  93290. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93291. return this;
  93292. }
  93293. if (this.useDefaultLoadingScreen) {
  93294. this._scene.getEngine().displayLoadingUI();
  93295. }
  93296. for (var index = 0; index < this._tasks.length; index++) {
  93297. var task = this._tasks[index];
  93298. this._runTask(task);
  93299. }
  93300. return this;
  93301. };
  93302. return AssetsManager;
  93303. }());
  93304. BABYLON.AssetsManager = AssetsManager;
  93305. })(BABYLON || (BABYLON = {}));
  93306. //# sourceMappingURL=babylon.assetsManager.js.map
  93307. var BABYLON;
  93308. (function (BABYLON) {
  93309. var serializedGeometries = [];
  93310. var serializeGeometry = function (geometry, serializationGeometries) {
  93311. if (serializedGeometries[geometry.id]) {
  93312. return;
  93313. }
  93314. if (geometry.doNotSerialize) {
  93315. return;
  93316. }
  93317. if (geometry instanceof BABYLON.BoxGeometry) {
  93318. serializationGeometries.boxes.push(geometry.serialize());
  93319. }
  93320. else if (geometry instanceof BABYLON.SphereGeometry) {
  93321. serializationGeometries.spheres.push(geometry.serialize());
  93322. }
  93323. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93324. serializationGeometries.cylinders.push(geometry.serialize());
  93325. }
  93326. else if (geometry instanceof BABYLON.TorusGeometry) {
  93327. serializationGeometries.toruses.push(geometry.serialize());
  93328. }
  93329. else if (geometry instanceof BABYLON.GroundGeometry) {
  93330. serializationGeometries.grounds.push(geometry.serialize());
  93331. }
  93332. else if (geometry instanceof BABYLON.Plane) {
  93333. serializationGeometries.planes.push(geometry.serialize());
  93334. }
  93335. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93336. serializationGeometries.torusKnots.push(geometry.serialize());
  93337. }
  93338. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93339. throw new Error("Unknown primitive type");
  93340. }
  93341. else {
  93342. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93343. }
  93344. serializedGeometries[geometry.id] = true;
  93345. };
  93346. var serializeMesh = function (mesh, serializationScene) {
  93347. var serializationObject = {};
  93348. // Geometry
  93349. var geometry = mesh._geometry;
  93350. if (geometry) {
  93351. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93352. // 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
  93353. serializeGeometry(geometry, serializationScene.geometries);
  93354. }
  93355. }
  93356. // Custom
  93357. if (mesh.serialize) {
  93358. mesh.serialize(serializationObject);
  93359. }
  93360. return serializationObject;
  93361. };
  93362. var finalizeSingleMesh = function (mesh, serializationObject) {
  93363. //only works if the mesh is already loaded
  93364. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93365. //serialize material
  93366. if (mesh.material) {
  93367. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93368. serializationObject.materials = serializationObject.materials || [];
  93369. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93370. serializationObject.materials.push(mesh.material.serialize());
  93371. }
  93372. }
  93373. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93374. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93375. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93376. serializationObject.multiMaterials.push(mesh.material.serialize());
  93377. }
  93378. }
  93379. }
  93380. //serialize geometry
  93381. var geometry = mesh._geometry;
  93382. if (geometry) {
  93383. if (!serializationObject.geometries) {
  93384. serializationObject.geometries = {};
  93385. serializationObject.geometries.boxes = [];
  93386. serializationObject.geometries.spheres = [];
  93387. serializationObject.geometries.cylinders = [];
  93388. serializationObject.geometries.toruses = [];
  93389. serializationObject.geometries.grounds = [];
  93390. serializationObject.geometries.planes = [];
  93391. serializationObject.geometries.torusKnots = [];
  93392. serializationObject.geometries.vertexData = [];
  93393. }
  93394. serializeGeometry(geometry, serializationObject.geometries);
  93395. }
  93396. // Skeletons
  93397. if (mesh.skeleton) {
  93398. serializationObject.skeletons = serializationObject.skeletons || [];
  93399. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93400. }
  93401. //serialize the actual mesh
  93402. serializationObject.meshes = serializationObject.meshes || [];
  93403. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93404. }
  93405. };
  93406. var SceneSerializer = /** @class */ (function () {
  93407. function SceneSerializer() {
  93408. }
  93409. SceneSerializer.ClearCache = function () {
  93410. serializedGeometries = [];
  93411. };
  93412. SceneSerializer.Serialize = function (scene) {
  93413. var serializationObject = {};
  93414. SceneSerializer.ClearCache();
  93415. // Scene
  93416. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93417. serializationObject.autoClear = scene.autoClear;
  93418. serializationObject.clearColor = scene.clearColor.asArray();
  93419. serializationObject.ambientColor = scene.ambientColor.asArray();
  93420. serializationObject.gravity = scene.gravity.asArray();
  93421. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93422. serializationObject.workerCollisions = scene.workerCollisions;
  93423. // Fog
  93424. if (scene.fogMode && scene.fogMode !== 0) {
  93425. serializationObject.fogMode = scene.fogMode;
  93426. serializationObject.fogColor = scene.fogColor.asArray();
  93427. serializationObject.fogStart = scene.fogStart;
  93428. serializationObject.fogEnd = scene.fogEnd;
  93429. serializationObject.fogDensity = scene.fogDensity;
  93430. }
  93431. //Physics
  93432. if (scene.isPhysicsEnabled()) {
  93433. var physicEngine = scene.getPhysicsEngine();
  93434. if (physicEngine) {
  93435. serializationObject.physicsEnabled = true;
  93436. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93437. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93438. }
  93439. }
  93440. // Metadata
  93441. if (scene.metadata) {
  93442. serializationObject.metadata = scene.metadata;
  93443. }
  93444. // Morph targets
  93445. serializationObject.morphTargetManagers = [];
  93446. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93447. var abstractMesh = _a[_i];
  93448. var manager = abstractMesh.morphTargetManager;
  93449. if (manager) {
  93450. serializationObject.morphTargetManagers.push(manager.serialize());
  93451. }
  93452. }
  93453. // Lights
  93454. serializationObject.lights = [];
  93455. var index;
  93456. var light;
  93457. for (index = 0; index < scene.lights.length; index++) {
  93458. light = scene.lights[index];
  93459. if (!light.doNotSerialize) {
  93460. serializationObject.lights.push(light.serialize());
  93461. }
  93462. }
  93463. // Cameras
  93464. serializationObject.cameras = [];
  93465. for (index = 0; index < scene.cameras.length; index++) {
  93466. var camera = scene.cameras[index];
  93467. if (!camera.doNotSerialize) {
  93468. serializationObject.cameras.push(camera.serialize());
  93469. }
  93470. }
  93471. if (scene.activeCamera) {
  93472. serializationObject.activeCameraID = scene.activeCamera.id;
  93473. }
  93474. // Animations
  93475. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93476. // Materials
  93477. serializationObject.materials = [];
  93478. serializationObject.multiMaterials = [];
  93479. var material;
  93480. for (index = 0; index < scene.materials.length; index++) {
  93481. material = scene.materials[index];
  93482. if (!material.doNotSerialize) {
  93483. serializationObject.materials.push(material.serialize());
  93484. }
  93485. }
  93486. // MultiMaterials
  93487. serializationObject.multiMaterials = [];
  93488. for (index = 0; index < scene.multiMaterials.length; index++) {
  93489. var multiMaterial = scene.multiMaterials[index];
  93490. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93491. }
  93492. // Environment texture
  93493. if (scene.environmentTexture) {
  93494. serializationObject.environmentTexture = scene.environmentTexture.name;
  93495. }
  93496. // Skeletons
  93497. serializationObject.skeletons = [];
  93498. for (index = 0; index < scene.skeletons.length; index++) {
  93499. var skeleton = scene.skeletons[index];
  93500. if (!skeleton.doNotSerialize) {
  93501. serializationObject.skeletons.push(skeleton.serialize());
  93502. }
  93503. }
  93504. // Transform nodes
  93505. serializationObject.transformNodes = [];
  93506. for (index = 0; index < scene.transformNodes.length; index++) {
  93507. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93508. }
  93509. // Geometries
  93510. serializationObject.geometries = {};
  93511. serializationObject.geometries.boxes = [];
  93512. serializationObject.geometries.spheres = [];
  93513. serializationObject.geometries.cylinders = [];
  93514. serializationObject.geometries.toruses = [];
  93515. serializationObject.geometries.grounds = [];
  93516. serializationObject.geometries.planes = [];
  93517. serializationObject.geometries.torusKnots = [];
  93518. serializationObject.geometries.vertexData = [];
  93519. serializedGeometries = [];
  93520. var geometries = scene.getGeometries();
  93521. for (index = 0; index < geometries.length; index++) {
  93522. var geometry = geometries[index];
  93523. if (geometry.isReady()) {
  93524. serializeGeometry(geometry, serializationObject.geometries);
  93525. }
  93526. }
  93527. // Meshes
  93528. serializationObject.meshes = [];
  93529. for (index = 0; index < scene.meshes.length; index++) {
  93530. var abstractMesh = scene.meshes[index];
  93531. if (abstractMesh instanceof BABYLON.Mesh) {
  93532. var mesh = abstractMesh;
  93533. if (!mesh.doNotSerialize) {
  93534. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93535. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93536. }
  93537. }
  93538. }
  93539. }
  93540. // Particles Systems
  93541. serializationObject.particleSystems = [];
  93542. for (index = 0; index < scene.particleSystems.length; index++) {
  93543. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93544. }
  93545. // Lens flares
  93546. serializationObject.lensFlareSystems = [];
  93547. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93548. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93549. }
  93550. // Shadows
  93551. serializationObject.shadowGenerators = [];
  93552. for (index = 0; index < scene.lights.length; index++) {
  93553. light = scene.lights[index];
  93554. var shadowGenerator = light.getShadowGenerator();
  93555. if (shadowGenerator) {
  93556. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93557. }
  93558. }
  93559. // Action Manager
  93560. if (scene.actionManager) {
  93561. serializationObject.actions = scene.actionManager.serialize("scene");
  93562. }
  93563. // Audio
  93564. serializationObject.sounds = [];
  93565. for (index = 0; index < scene.soundTracks.length; index++) {
  93566. var soundtrack = scene.soundTracks[index];
  93567. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93568. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93569. }
  93570. }
  93571. // Effect layers
  93572. serializationObject.effectLayers = [];
  93573. for (index = 0; index < scene.effectLayers.length; index++) {
  93574. var layer = scene.effectLayers[index];
  93575. if (layer.serialize) {
  93576. serializationObject.effectLayers.push(layer.serialize());
  93577. }
  93578. }
  93579. return serializationObject;
  93580. };
  93581. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93582. if (withParents === void 0) { withParents = false; }
  93583. if (withChildren === void 0) { withChildren = false; }
  93584. var serializationObject = {};
  93585. SceneSerializer.ClearCache();
  93586. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93587. if (withParents || withChildren) {
  93588. //deliberate for loop! not for each, appended should be processed as well.
  93589. for (var i = 0; i < toSerialize.length; ++i) {
  93590. if (withChildren) {
  93591. toSerialize[i].getDescendants().forEach(function (node) {
  93592. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93593. toSerialize.push(node);
  93594. }
  93595. });
  93596. }
  93597. //make sure the array doesn't contain the object already
  93598. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93599. toSerialize.push(toSerialize[i].parent);
  93600. }
  93601. }
  93602. }
  93603. toSerialize.forEach(function (mesh) {
  93604. finalizeSingleMesh(mesh, serializationObject);
  93605. });
  93606. return serializationObject;
  93607. };
  93608. return SceneSerializer;
  93609. }());
  93610. BABYLON.SceneSerializer = SceneSerializer;
  93611. })(BABYLON || (BABYLON = {}));
  93612. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93613. var BABYLON;
  93614. (function (BABYLON) {
  93615. var ReflectionProbe = /** @class */ (function () {
  93616. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93617. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93618. var _this = this;
  93619. this.name = name;
  93620. this._viewMatrix = BABYLON.Matrix.Identity();
  93621. this._target = BABYLON.Vector3.Zero();
  93622. this._add = BABYLON.Vector3.Zero();
  93623. this._invertYAxis = false;
  93624. this.position = BABYLON.Vector3.Zero();
  93625. this._scene = scene;
  93626. this._scene.reflectionProbes.push(this);
  93627. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93628. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93629. switch (faceIndex) {
  93630. case 0:
  93631. _this._add.copyFromFloats(1, 0, 0);
  93632. break;
  93633. case 1:
  93634. _this._add.copyFromFloats(-1, 0, 0);
  93635. break;
  93636. case 2:
  93637. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93638. break;
  93639. case 3:
  93640. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93641. break;
  93642. case 4:
  93643. _this._add.copyFromFloats(0, 0, 1);
  93644. break;
  93645. case 5:
  93646. _this._add.copyFromFloats(0, 0, -1);
  93647. break;
  93648. }
  93649. if (_this._attachedMesh) {
  93650. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93651. }
  93652. _this.position.addToRef(_this._add, _this._target);
  93653. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93654. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93655. scene._forcedViewPosition = _this.position;
  93656. });
  93657. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93658. scene._forcedViewPosition = null;
  93659. scene.updateTransformMatrix(true);
  93660. });
  93661. if (scene.activeCamera) {
  93662. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93663. }
  93664. }
  93665. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93666. get: function () {
  93667. return this._renderTargetTexture.samples;
  93668. },
  93669. set: function (value) {
  93670. this._renderTargetTexture.samples = value;
  93671. },
  93672. enumerable: true,
  93673. configurable: true
  93674. });
  93675. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93676. get: function () {
  93677. return this._renderTargetTexture.refreshRate;
  93678. },
  93679. set: function (value) {
  93680. this._renderTargetTexture.refreshRate = value;
  93681. },
  93682. enumerable: true,
  93683. configurable: true
  93684. });
  93685. ReflectionProbe.prototype.getScene = function () {
  93686. return this._scene;
  93687. };
  93688. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93689. get: function () {
  93690. return this._renderTargetTexture;
  93691. },
  93692. enumerable: true,
  93693. configurable: true
  93694. });
  93695. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93696. get: function () {
  93697. return this._renderTargetTexture.renderList;
  93698. },
  93699. enumerable: true,
  93700. configurable: true
  93701. });
  93702. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93703. this._attachedMesh = mesh;
  93704. };
  93705. /**
  93706. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93707. *
  93708. * @param renderingGroupId The rendering group id corresponding to its index
  93709. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93710. */
  93711. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93712. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93713. };
  93714. ReflectionProbe.prototype.dispose = function () {
  93715. var index = this._scene.reflectionProbes.indexOf(this);
  93716. if (index !== -1) {
  93717. // Remove from the scene if found
  93718. this._scene.reflectionProbes.splice(index, 1);
  93719. }
  93720. if (this._renderTargetTexture) {
  93721. this._renderTargetTexture.dispose();
  93722. this._renderTargetTexture = null;
  93723. }
  93724. };
  93725. return ReflectionProbe;
  93726. }());
  93727. BABYLON.ReflectionProbe = ReflectionProbe;
  93728. })(BABYLON || (BABYLON = {}));
  93729. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93730. var BABYLON;
  93731. (function (BABYLON) {
  93732. var Layer = /** @class */ (function () {
  93733. function Layer(name, imgUrl, scene, isBackground, color) {
  93734. this.name = name;
  93735. this.scale = new BABYLON.Vector2(1, 1);
  93736. this.offset = new BABYLON.Vector2(0, 0);
  93737. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93738. this.layerMask = 0x0FFFFFFF;
  93739. this._vertexBuffers = {};
  93740. // Events
  93741. /**
  93742. * An event triggered when the layer is disposed.
  93743. */
  93744. this.onDisposeObservable = new BABYLON.Observable();
  93745. /**
  93746. * An event triggered before rendering the scene
  93747. */
  93748. this.onBeforeRenderObservable = new BABYLON.Observable();
  93749. /**
  93750. * An event triggered after rendering the scene
  93751. */
  93752. this.onAfterRenderObservable = new BABYLON.Observable();
  93753. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93754. this.isBackground = isBackground === undefined ? true : isBackground;
  93755. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93756. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93757. this._scene.layers.push(this);
  93758. var engine = this._scene.getEngine();
  93759. // VBO
  93760. var vertices = [];
  93761. vertices.push(1, 1);
  93762. vertices.push(-1, 1);
  93763. vertices.push(-1, -1);
  93764. vertices.push(1, -1);
  93765. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93766. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93767. this._createIndexBuffer();
  93768. // Effects
  93769. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93770. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93771. }
  93772. Object.defineProperty(Layer.prototype, "onDispose", {
  93773. set: function (callback) {
  93774. if (this._onDisposeObserver) {
  93775. this.onDisposeObservable.remove(this._onDisposeObserver);
  93776. }
  93777. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93778. },
  93779. enumerable: true,
  93780. configurable: true
  93781. });
  93782. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93783. set: function (callback) {
  93784. if (this._onBeforeRenderObserver) {
  93785. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93786. }
  93787. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93788. },
  93789. enumerable: true,
  93790. configurable: true
  93791. });
  93792. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93793. set: function (callback) {
  93794. if (this._onAfterRenderObserver) {
  93795. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93796. }
  93797. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93798. },
  93799. enumerable: true,
  93800. configurable: true
  93801. });
  93802. Layer.prototype._createIndexBuffer = function () {
  93803. var engine = this._scene.getEngine();
  93804. // Indices
  93805. var indices = [];
  93806. indices.push(0);
  93807. indices.push(1);
  93808. indices.push(2);
  93809. indices.push(0);
  93810. indices.push(2);
  93811. indices.push(3);
  93812. this._indexBuffer = engine.createIndexBuffer(indices);
  93813. };
  93814. Layer.prototype._rebuild = function () {
  93815. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93816. if (vb) {
  93817. vb._rebuild();
  93818. }
  93819. this._createIndexBuffer();
  93820. };
  93821. Layer.prototype.render = function () {
  93822. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93823. // Check
  93824. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93825. return;
  93826. var engine = this._scene.getEngine();
  93827. this.onBeforeRenderObservable.notifyObservers(this);
  93828. // Render
  93829. engine.enableEffect(currentEffect);
  93830. engine.setState(false);
  93831. // Texture
  93832. currentEffect.setTexture("textureSampler", this.texture);
  93833. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93834. // Color
  93835. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93836. // Scale / offset
  93837. currentEffect.setVector2("offset", this.offset);
  93838. currentEffect.setVector2("scale", this.scale);
  93839. // VBOs
  93840. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93841. // Draw order
  93842. if (!this.alphaTest) {
  93843. engine.setAlphaMode(this.alphaBlendingMode);
  93844. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93845. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93846. }
  93847. else {
  93848. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93849. }
  93850. this.onAfterRenderObservable.notifyObservers(this);
  93851. };
  93852. Layer.prototype.dispose = function () {
  93853. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93854. if (vertexBuffer) {
  93855. vertexBuffer.dispose();
  93856. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93857. }
  93858. if (this._indexBuffer) {
  93859. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93860. this._indexBuffer = null;
  93861. }
  93862. if (this.texture) {
  93863. this.texture.dispose();
  93864. this.texture = null;
  93865. }
  93866. // Remove from scene
  93867. var index = this._scene.layers.indexOf(this);
  93868. this._scene.layers.splice(index, 1);
  93869. // Callback
  93870. this.onDisposeObservable.notifyObservers(this);
  93871. this.onDisposeObservable.clear();
  93872. this.onAfterRenderObservable.clear();
  93873. this.onBeforeRenderObservable.clear();
  93874. };
  93875. return Layer;
  93876. }());
  93877. BABYLON.Layer = Layer;
  93878. })(BABYLON || (BABYLON = {}));
  93879. //# sourceMappingURL=babylon.layer.js.map
  93880. var BABYLON;
  93881. (function (BABYLON) {
  93882. var TextureTools = /** @class */ (function () {
  93883. function TextureTools() {
  93884. }
  93885. /**
  93886. * Uses the GPU to create a copy texture rescaled at a given size
  93887. * @param texture Texture to copy from
  93888. * @param width Desired width
  93889. * @param height Desired height
  93890. * @return Generated texture
  93891. */
  93892. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93893. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93894. var scene = texture.getScene();
  93895. var engine = scene.getEngine();
  93896. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93897. rtt.wrapU = texture.wrapU;
  93898. rtt.wrapV = texture.wrapV;
  93899. rtt.uOffset = texture.uOffset;
  93900. rtt.vOffset = texture.vOffset;
  93901. rtt.uScale = texture.uScale;
  93902. rtt.vScale = texture.vScale;
  93903. rtt.uAng = texture.uAng;
  93904. rtt.vAng = texture.vAng;
  93905. rtt.wAng = texture.wAng;
  93906. rtt.coordinatesIndex = texture.coordinatesIndex;
  93907. rtt.level = texture.level;
  93908. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93909. rtt._texture.isReady = false;
  93910. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93911. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93912. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93913. passPostProcess.getEffect().executeWhenCompiled(function () {
  93914. passPostProcess.onApply = function (effect) {
  93915. effect.setTexture("textureSampler", texture);
  93916. };
  93917. var internalTexture = rtt.getInternalTexture();
  93918. if (internalTexture) {
  93919. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93920. engine.unBindFramebuffer(internalTexture);
  93921. rtt.disposeFramebufferObjects();
  93922. passPostProcess.dispose();
  93923. internalTexture.isReady = true;
  93924. }
  93925. });
  93926. return rtt;
  93927. };
  93928. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93929. if (!scene._environmentBRDFTexture) {
  93930. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93931. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93932. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93933. scene._environmentBRDFTexture = texture;
  93934. }
  93935. return scene._environmentBRDFTexture;
  93936. };
  93937. 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=";
  93938. return TextureTools;
  93939. }());
  93940. BABYLON.TextureTools = TextureTools;
  93941. })(BABYLON || (BABYLON = {}));
  93942. //# sourceMappingURL=babylon.textureTools.js.map
  93943. var BABYLON;
  93944. (function (BABYLON) {
  93945. var FramingBehavior = /** @class */ (function () {
  93946. function FramingBehavior() {
  93947. this._mode = FramingBehavior.FitFrustumSidesMode;
  93948. this._radiusScale = 1.0;
  93949. this._positionScale = 0.5;
  93950. this._defaultElevation = 0.3;
  93951. this._elevationReturnTime = 1500;
  93952. this._elevationReturnWaitTime = 1000;
  93953. this._zoomStopsAnimation = false;
  93954. this._framingTime = 1500;
  93955. this._isPointerDown = false;
  93956. this._lastInteractionTime = -Infinity;
  93957. // Framing control
  93958. this._animatables = new Array();
  93959. this._betaIsAnimating = false;
  93960. }
  93961. Object.defineProperty(FramingBehavior.prototype, "name", {
  93962. get: function () {
  93963. return "Framing";
  93964. },
  93965. enumerable: true,
  93966. configurable: true
  93967. });
  93968. Object.defineProperty(FramingBehavior.prototype, "mode", {
  93969. /**
  93970. * Gets current mode used by the behavior.
  93971. */
  93972. get: function () {
  93973. return this._mode;
  93974. },
  93975. /**
  93976. * Sets the current mode used by the behavior
  93977. */
  93978. set: function (mode) {
  93979. this._mode = mode;
  93980. },
  93981. enumerable: true,
  93982. configurable: true
  93983. });
  93984. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  93985. /**
  93986. * Gets the scale applied to the radius
  93987. */
  93988. get: function () {
  93989. return this._radiusScale;
  93990. },
  93991. /**
  93992. * Sets the scale applied to the radius (1 by default)
  93993. */
  93994. set: function (radius) {
  93995. this._radiusScale = radius;
  93996. },
  93997. enumerable: true,
  93998. configurable: true
  93999. });
  94000. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94001. /**
  94002. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94003. */
  94004. get: function () {
  94005. return this._positionScale;
  94006. },
  94007. /**
  94008. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94009. */
  94010. set: function (scale) {
  94011. this._positionScale = scale;
  94012. },
  94013. enumerable: true,
  94014. configurable: true
  94015. });
  94016. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94017. /**
  94018. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94019. * behaviour is triggered, in radians.
  94020. */
  94021. get: function () {
  94022. return this._defaultElevation;
  94023. },
  94024. /**
  94025. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94026. * behaviour is triggered, in radians.
  94027. */
  94028. set: function (elevation) {
  94029. this._defaultElevation = elevation;
  94030. },
  94031. enumerable: true,
  94032. configurable: true
  94033. });
  94034. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94035. /**
  94036. * Gets the time (in milliseconds) taken to return to the default beta position.
  94037. * Negative value indicates camera should not return to default.
  94038. */
  94039. get: function () {
  94040. return this._elevationReturnTime;
  94041. },
  94042. /**
  94043. * Sets the time (in milliseconds) taken to return to the default beta position.
  94044. * Negative value indicates camera should not return to default.
  94045. */
  94046. set: function (speed) {
  94047. this._elevationReturnTime = speed;
  94048. },
  94049. enumerable: true,
  94050. configurable: true
  94051. });
  94052. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94053. /**
  94054. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94055. */
  94056. get: function () {
  94057. return this._elevationReturnWaitTime;
  94058. },
  94059. /**
  94060. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94061. */
  94062. set: function (time) {
  94063. this._elevationReturnWaitTime = time;
  94064. },
  94065. enumerable: true,
  94066. configurable: true
  94067. });
  94068. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94069. /**
  94070. * Gets the flag that indicates if user zooming should stop animation.
  94071. */
  94072. get: function () {
  94073. return this._zoomStopsAnimation;
  94074. },
  94075. /**
  94076. * Sets the flag that indicates if user zooming should stop animation.
  94077. */
  94078. set: function (flag) {
  94079. this._zoomStopsAnimation = flag;
  94080. },
  94081. enumerable: true,
  94082. configurable: true
  94083. });
  94084. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94085. /**
  94086. * Gets the transition time when framing the mesh, in milliseconds
  94087. */
  94088. get: function () {
  94089. return this._framingTime;
  94090. },
  94091. /**
  94092. * Sets the transition time when framing the mesh, in milliseconds
  94093. */
  94094. set: function (time) {
  94095. this._framingTime = time;
  94096. },
  94097. enumerable: true,
  94098. configurable: true
  94099. });
  94100. FramingBehavior.prototype.init = function () {
  94101. // Do notihng
  94102. };
  94103. FramingBehavior.prototype.attach = function (camera) {
  94104. var _this = this;
  94105. this._attachedCamera = camera;
  94106. var scene = this._attachedCamera.getScene();
  94107. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94108. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94109. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94110. _this._isPointerDown = true;
  94111. return;
  94112. }
  94113. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94114. _this._isPointerDown = false;
  94115. }
  94116. });
  94117. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94118. if (mesh) {
  94119. _this.zoomOnMesh(mesh);
  94120. }
  94121. });
  94122. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94123. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94124. _this._applyUserInteraction();
  94125. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94126. // back to the default position after a given timeout
  94127. _this._maintainCameraAboveGround();
  94128. });
  94129. };
  94130. FramingBehavior.prototype.detach = function () {
  94131. if (!this._attachedCamera) {
  94132. return;
  94133. }
  94134. var scene = this._attachedCamera.getScene();
  94135. if (this._onPrePointerObservableObserver) {
  94136. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94137. }
  94138. if (this._onAfterCheckInputsObserver) {
  94139. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94140. }
  94141. if (this._onMeshTargetChangedObserver) {
  94142. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94143. }
  94144. this._attachedCamera = null;
  94145. };
  94146. /**
  94147. * Targets the given mesh and updates zoom level accordingly.
  94148. * @param mesh The mesh to target.
  94149. * @param radius Optional. If a cached radius position already exists, overrides default.
  94150. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94151. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94152. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94153. */
  94154. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94155. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94156. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94157. mesh.computeWorldMatrix(true);
  94158. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94159. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94160. };
  94161. /**
  94162. * Targets the given mesh with its children and updates zoom level accordingly.
  94163. * @param mesh The mesh to target.
  94164. * @param radius Optional. If a cached radius position already exists, overrides default.
  94165. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94166. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94167. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94168. */
  94169. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94170. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94171. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94172. mesh.computeWorldMatrix(true);
  94173. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94174. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94175. };
  94176. /**
  94177. * Targets the given meshes with their children and updates zoom level accordingly.
  94178. * @param meshes The mesh to target.
  94179. * @param radius Optional. If a cached radius position already exists, overrides default.
  94180. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94181. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94182. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94183. */
  94184. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94185. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94186. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94187. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94188. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94189. for (var i = 0; i < meshes.length; i++) {
  94190. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94191. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94192. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94193. }
  94194. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94195. };
  94196. /**
  94197. * Targets the given mesh and updates zoom level accordingly.
  94198. * @param mesh The mesh to target.
  94199. * @param radius Optional. If a cached radius position already exists, overrides default.
  94200. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94201. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94202. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94203. */
  94204. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94205. var _this = this;
  94206. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94207. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94208. var zoomTarget;
  94209. if (!this._attachedCamera) {
  94210. return;
  94211. }
  94212. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94213. var bottom = minimumWorld.y;
  94214. var top = maximumWorld.y;
  94215. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94216. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94217. if (focusOnOriginXZ) {
  94218. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94219. }
  94220. else {
  94221. var centerWorld = minimumWorld.add(radiusWorld);
  94222. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94223. }
  94224. if (!this._vectorTransition) {
  94225. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94226. }
  94227. this._betaIsAnimating = true;
  94228. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94229. if (animatable) {
  94230. this._animatables.push(animatable);
  94231. }
  94232. // sets the radius and lower radius bounds
  94233. // Small delta ensures camera is not always at lower zoom limit.
  94234. var radius = 0;
  94235. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94236. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94237. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94238. radius = position;
  94239. }
  94240. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94241. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94242. if (this._attachedCamera.lowerRadiusLimit === null) {
  94243. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94244. }
  94245. }
  94246. // Set sensibilities
  94247. var extend = maximumWorld.subtract(minimumWorld).length();
  94248. this._attachedCamera.panningSensibility = 5000 / extend;
  94249. this._attachedCamera.wheelPrecision = 100 / radius;
  94250. // transition to new radius
  94251. if (!this._radiusTransition) {
  94252. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94253. }
  94254. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94255. _this.stopAllAnimations();
  94256. if (onAnimationEnd) {
  94257. onAnimationEnd();
  94258. }
  94259. if (_this._attachedCamera) {
  94260. _this._attachedCamera.storeState();
  94261. }
  94262. });
  94263. if (animatable) {
  94264. this._animatables.push(animatable);
  94265. }
  94266. };
  94267. /**
  94268. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94269. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94270. * frustum width.
  94271. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94272. * to fully enclose the mesh in the viewing frustum.
  94273. */
  94274. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94275. var size = maximumWorld.subtract(minimumWorld);
  94276. var boxVectorGlobalDiagonal = size.length();
  94277. var frustumSlope = this._getFrustumSlope();
  94278. // Formula for setting distance
  94279. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94280. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94281. // Horizon distance
  94282. var radius = radiusWithoutFraming * this._radiusScale;
  94283. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94284. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94285. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94286. var camera = this._attachedCamera;
  94287. if (!camera) {
  94288. return 0;
  94289. }
  94290. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94291. // Don't exceed the requested limit
  94292. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94293. }
  94294. // Don't exceed the upper radius limit
  94295. if (camera.upperRadiusLimit) {
  94296. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94297. }
  94298. return distance;
  94299. };
  94300. /**
  94301. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94302. * is automatically returned to its default position (expected to be above ground plane).
  94303. */
  94304. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94305. var _this = this;
  94306. if (this._elevationReturnTime < 0) {
  94307. return;
  94308. }
  94309. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94310. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94311. var limitBeta = Math.PI * 0.5;
  94312. // Bring the camera back up if below the ground plane
  94313. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94314. this._betaIsAnimating = true;
  94315. //Transition to new position
  94316. this.stopAllAnimations();
  94317. if (!this._betaTransition) {
  94318. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94319. }
  94320. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94321. _this._clearAnimationLocks();
  94322. _this.stopAllAnimations();
  94323. });
  94324. if (animatabe) {
  94325. this._animatables.push(animatabe);
  94326. }
  94327. }
  94328. };
  94329. /**
  94330. * Returns the frustum slope based on the canvas ratio and camera FOV
  94331. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94332. */
  94333. FramingBehavior.prototype._getFrustumSlope = function () {
  94334. // Calculate the viewport ratio
  94335. // Aspect Ratio is Height/Width.
  94336. var camera = this._attachedCamera;
  94337. if (!camera) {
  94338. return BABYLON.Vector2.Zero();
  94339. }
  94340. var engine = camera.getScene().getEngine();
  94341. var aspectRatio = engine.getAspectRatio(camera);
  94342. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94343. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94344. var frustumSlopeY = Math.tan(camera.fov / 2);
  94345. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94346. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94347. // along the forward vector.
  94348. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94349. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94350. };
  94351. /**
  94352. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94353. */
  94354. FramingBehavior.prototype._clearAnimationLocks = function () {
  94355. this._betaIsAnimating = false;
  94356. };
  94357. /**
  94358. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94359. */
  94360. FramingBehavior.prototype._applyUserInteraction = function () {
  94361. if (this.isUserIsMoving) {
  94362. this._lastInteractionTime = BABYLON.Tools.Now;
  94363. this.stopAllAnimations();
  94364. this._clearAnimationLocks();
  94365. }
  94366. };
  94367. /**
  94368. * Stops and removes all animations that have been applied to the camera
  94369. */
  94370. FramingBehavior.prototype.stopAllAnimations = function () {
  94371. if (this._attachedCamera) {
  94372. this._attachedCamera.animations = [];
  94373. }
  94374. while (this._animatables.length) {
  94375. if (this._animatables[0]) {
  94376. this._animatables[0].onAnimationEnd = null;
  94377. this._animatables[0].stop();
  94378. }
  94379. this._animatables.shift();
  94380. }
  94381. };
  94382. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94383. /**
  94384. * Gets a value indicating if the user is moving the camera
  94385. */
  94386. get: function () {
  94387. if (!this._attachedCamera) {
  94388. return false;
  94389. }
  94390. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94391. this._attachedCamera.inertialBetaOffset !== 0 ||
  94392. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94393. this._attachedCamera.inertialPanningX !== 0 ||
  94394. this._attachedCamera.inertialPanningY !== 0 ||
  94395. this._isPointerDown;
  94396. },
  94397. enumerable: true,
  94398. configurable: true
  94399. });
  94400. /**
  94401. * The easing function used by animations
  94402. */
  94403. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94404. /**
  94405. * The easing mode used by animations
  94406. */
  94407. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94408. // Statics
  94409. /**
  94410. * The camera can move all the way towards the mesh.
  94411. */
  94412. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94413. /**
  94414. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94415. */
  94416. FramingBehavior.FitFrustumSidesMode = 1;
  94417. return FramingBehavior;
  94418. }());
  94419. BABYLON.FramingBehavior = FramingBehavior;
  94420. })(BABYLON || (BABYLON = {}));
  94421. //# sourceMappingURL=babylon.framingBehavior.js.map
  94422. var BABYLON;
  94423. (function (BABYLON) {
  94424. /**
  94425. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94426. */
  94427. var BouncingBehavior = /** @class */ (function () {
  94428. function BouncingBehavior() {
  94429. /**
  94430. * The duration of the animation, in milliseconds
  94431. */
  94432. this.transitionDuration = 450;
  94433. /**
  94434. * Length of the distance animated by the transition when lower radius is reached
  94435. */
  94436. this.lowerRadiusTransitionRange = 2;
  94437. /**
  94438. * Length of the distance animated by the transition when upper radius is reached
  94439. */
  94440. this.upperRadiusTransitionRange = -2;
  94441. this._autoTransitionRange = false;
  94442. // Animations
  94443. this._radiusIsAnimating = false;
  94444. this._radiusBounceTransition = null;
  94445. this._animatables = new Array();
  94446. }
  94447. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94448. get: function () {
  94449. return "Bouncing";
  94450. },
  94451. enumerable: true,
  94452. configurable: true
  94453. });
  94454. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94455. /**
  94456. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94457. */
  94458. get: function () {
  94459. return this._autoTransitionRange;
  94460. },
  94461. /**
  94462. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94463. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94464. */
  94465. set: function (value) {
  94466. var _this = this;
  94467. if (this._autoTransitionRange === value) {
  94468. return;
  94469. }
  94470. this._autoTransitionRange = value;
  94471. var camera = this._attachedCamera;
  94472. if (!camera) {
  94473. return;
  94474. }
  94475. if (value) {
  94476. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94477. if (!mesh) {
  94478. return;
  94479. }
  94480. mesh.computeWorldMatrix(true);
  94481. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94482. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94483. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94484. });
  94485. }
  94486. else if (this._onMeshTargetChangedObserver) {
  94487. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94488. }
  94489. },
  94490. enumerable: true,
  94491. configurable: true
  94492. });
  94493. BouncingBehavior.prototype.init = function () {
  94494. // Do notihng
  94495. };
  94496. BouncingBehavior.prototype.attach = function (camera) {
  94497. var _this = this;
  94498. this._attachedCamera = camera;
  94499. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94500. if (!_this._attachedCamera) {
  94501. return;
  94502. }
  94503. // Add the bounce animation to the lower radius limit
  94504. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94505. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94506. }
  94507. // Add the bounce animation to the upper radius limit
  94508. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94509. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94510. }
  94511. });
  94512. };
  94513. BouncingBehavior.prototype.detach = function () {
  94514. if (!this._attachedCamera) {
  94515. return;
  94516. }
  94517. if (this._onAfterCheckInputsObserver) {
  94518. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94519. }
  94520. if (this._onMeshTargetChangedObserver) {
  94521. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94522. }
  94523. this._attachedCamera = null;
  94524. };
  94525. /**
  94526. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94527. * @param radiusLimit The limit to check against.
  94528. * @return Bool to indicate if at limit.
  94529. */
  94530. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94531. if (!this._attachedCamera) {
  94532. return false;
  94533. }
  94534. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94535. return true;
  94536. }
  94537. return false;
  94538. };
  94539. /**
  94540. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94541. * @param radiusDelta The delta by which to animate to. Can be negative.
  94542. */
  94543. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94544. var _this = this;
  94545. if (!this._attachedCamera) {
  94546. return;
  94547. }
  94548. if (!this._radiusBounceTransition) {
  94549. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94550. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94551. }
  94552. // Prevent zoom until bounce has completed
  94553. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94554. this._attachedCamera.wheelPrecision = Infinity;
  94555. this._attachedCamera.inertialRadiusOffset = 0;
  94556. // Animate to the radius limit
  94557. this.stopAllAnimations();
  94558. this._radiusIsAnimating = true;
  94559. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94560. if (animatable) {
  94561. this._animatables.push(animatable);
  94562. }
  94563. };
  94564. /**
  94565. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94566. */
  94567. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94568. this._radiusIsAnimating = false;
  94569. if (this._attachedCamera) {
  94570. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94571. }
  94572. };
  94573. /**
  94574. * Stops and removes all animations that have been applied to the camera
  94575. */
  94576. BouncingBehavior.prototype.stopAllAnimations = function () {
  94577. if (this._attachedCamera) {
  94578. this._attachedCamera.animations = [];
  94579. }
  94580. while (this._animatables.length) {
  94581. this._animatables[0].onAnimationEnd = null;
  94582. this._animatables[0].stop();
  94583. this._animatables.shift();
  94584. }
  94585. };
  94586. /**
  94587. * The easing function used by animations
  94588. */
  94589. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94590. /**
  94591. * The easing mode used by animations
  94592. */
  94593. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94594. return BouncingBehavior;
  94595. }());
  94596. BABYLON.BouncingBehavior = BouncingBehavior;
  94597. })(BABYLON || (BABYLON = {}));
  94598. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94599. var BABYLON;
  94600. (function (BABYLON) {
  94601. var AutoRotationBehavior = /** @class */ (function () {
  94602. function AutoRotationBehavior() {
  94603. this._zoomStopsAnimation = false;
  94604. this._idleRotationSpeed = 0.05;
  94605. this._idleRotationWaitTime = 2000;
  94606. this._idleRotationSpinupTime = 2000;
  94607. this._isPointerDown = false;
  94608. this._lastFrameTime = null;
  94609. this._lastInteractionTime = -Infinity;
  94610. this._cameraRotationSpeed = 0;
  94611. this._lastFrameRadius = 0;
  94612. }
  94613. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94614. get: function () {
  94615. return "AutoRotation";
  94616. },
  94617. enumerable: true,
  94618. configurable: true
  94619. });
  94620. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94621. /**
  94622. * Gets the flag that indicates if user zooming should stop animation.
  94623. */
  94624. get: function () {
  94625. return this._zoomStopsAnimation;
  94626. },
  94627. /**
  94628. * Sets the flag that indicates if user zooming should stop animation.
  94629. */
  94630. set: function (flag) {
  94631. this._zoomStopsAnimation = flag;
  94632. },
  94633. enumerable: true,
  94634. configurable: true
  94635. });
  94636. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94637. /**
  94638. * Gets the default speed at which the camera rotates around the model.
  94639. */
  94640. get: function () {
  94641. return this._idleRotationSpeed;
  94642. },
  94643. /**
  94644. * Sets the default speed at which the camera rotates around the model.
  94645. */
  94646. set: function (speed) {
  94647. this._idleRotationSpeed = speed;
  94648. },
  94649. enumerable: true,
  94650. configurable: true
  94651. });
  94652. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94653. /**
  94654. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94655. */
  94656. get: function () {
  94657. return this._idleRotationWaitTime;
  94658. },
  94659. /**
  94660. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94661. */
  94662. set: function (time) {
  94663. this._idleRotationWaitTime = time;
  94664. },
  94665. enumerable: true,
  94666. configurable: true
  94667. });
  94668. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94669. /**
  94670. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94671. */
  94672. get: function () {
  94673. return this._idleRotationSpinupTime;
  94674. },
  94675. /**
  94676. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94677. */
  94678. set: function (time) {
  94679. this._idleRotationSpinupTime = time;
  94680. },
  94681. enumerable: true,
  94682. configurable: true
  94683. });
  94684. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94685. /**
  94686. * Gets a value indicating if the camera is currently rotating because of this behavior
  94687. */
  94688. get: function () {
  94689. return Math.abs(this._cameraRotationSpeed) > 0;
  94690. },
  94691. enumerable: true,
  94692. configurable: true
  94693. });
  94694. AutoRotationBehavior.prototype.init = function () {
  94695. // Do notihng
  94696. };
  94697. AutoRotationBehavior.prototype.attach = function (camera) {
  94698. var _this = this;
  94699. this._attachedCamera = camera;
  94700. var scene = this._attachedCamera.getScene();
  94701. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94702. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94703. _this._isPointerDown = true;
  94704. return;
  94705. }
  94706. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94707. _this._isPointerDown = false;
  94708. }
  94709. });
  94710. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94711. var now = BABYLON.Tools.Now;
  94712. var dt = 0;
  94713. if (_this._lastFrameTime != null) {
  94714. dt = now - _this._lastFrameTime;
  94715. }
  94716. _this._lastFrameTime = now;
  94717. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94718. _this._applyUserInteraction();
  94719. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94720. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94721. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94722. // Step camera rotation by rotation speed
  94723. if (_this._attachedCamera) {
  94724. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94725. }
  94726. });
  94727. };
  94728. AutoRotationBehavior.prototype.detach = function () {
  94729. if (!this._attachedCamera) {
  94730. return;
  94731. }
  94732. var scene = this._attachedCamera.getScene();
  94733. if (this._onPrePointerObservableObserver) {
  94734. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94735. }
  94736. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94737. this._attachedCamera = null;
  94738. };
  94739. /**
  94740. * Returns true if user is scrolling.
  94741. * @return true if user is scrolling.
  94742. */
  94743. AutoRotationBehavior.prototype._userIsZooming = function () {
  94744. if (!this._attachedCamera) {
  94745. return false;
  94746. }
  94747. return this._attachedCamera.inertialRadiusOffset !== 0;
  94748. };
  94749. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94750. if (!this._attachedCamera) {
  94751. return false;
  94752. }
  94753. var zoomHasHitLimit = false;
  94754. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94755. zoomHasHitLimit = true;
  94756. }
  94757. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94758. this._lastFrameRadius = this._attachedCamera.radius;
  94759. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94760. };
  94761. /**
  94762. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94763. */
  94764. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94765. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94766. this._lastInteractionTime = BABYLON.Tools.Now;
  94767. }
  94768. };
  94769. // Tools
  94770. AutoRotationBehavior.prototype._userIsMoving = function () {
  94771. if (!this._attachedCamera) {
  94772. return false;
  94773. }
  94774. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94775. this._attachedCamera.inertialBetaOffset !== 0 ||
  94776. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94777. this._attachedCamera.inertialPanningX !== 0 ||
  94778. this._attachedCamera.inertialPanningY !== 0 ||
  94779. this._isPointerDown;
  94780. };
  94781. return AutoRotationBehavior;
  94782. }());
  94783. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94784. })(BABYLON || (BABYLON = {}));
  94785. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94786. var BABYLON;
  94787. (function (BABYLON) {
  94788. var NullEngineOptions = /** @class */ (function () {
  94789. function NullEngineOptions() {
  94790. this.renderWidth = 512;
  94791. this.renderHeight = 256;
  94792. this.textureSize = 512;
  94793. this.deterministicLockstep = false;
  94794. this.lockstepMaxSteps = 4;
  94795. }
  94796. return NullEngineOptions;
  94797. }());
  94798. BABYLON.NullEngineOptions = NullEngineOptions;
  94799. /**
  94800. * The null engine class provides support for headless version of babylon.js.
  94801. * This can be used in server side scenario or for testing purposes
  94802. */
  94803. var NullEngine = /** @class */ (function (_super) {
  94804. __extends(NullEngine, _super);
  94805. function NullEngine(options) {
  94806. if (options === void 0) { options = new NullEngineOptions(); }
  94807. var _this = _super.call(this, null) || this;
  94808. if (options.deterministicLockstep === undefined) {
  94809. options.deterministicLockstep = false;
  94810. }
  94811. if (options.lockstepMaxSteps === undefined) {
  94812. options.lockstepMaxSteps = 4;
  94813. }
  94814. _this._options = options;
  94815. // Init caps
  94816. // We consider we are on a webgl1 capable device
  94817. _this._caps = new BABYLON.EngineCapabilities();
  94818. _this._caps.maxTexturesImageUnits = 16;
  94819. _this._caps.maxVertexTextureImageUnits = 16;
  94820. _this._caps.maxTextureSize = 512;
  94821. _this._caps.maxCubemapTextureSize = 512;
  94822. _this._caps.maxRenderTextureSize = 512;
  94823. _this._caps.maxVertexAttribs = 16;
  94824. _this._caps.maxVaryingVectors = 16;
  94825. _this._caps.maxFragmentUniformVectors = 16;
  94826. _this._caps.maxVertexUniformVectors = 16;
  94827. // Extensions
  94828. _this._caps.standardDerivatives = false;
  94829. _this._caps.astc = null;
  94830. _this._caps.s3tc = null;
  94831. _this._caps.pvrtc = null;
  94832. _this._caps.etc1 = null;
  94833. _this._caps.etc2 = null;
  94834. _this._caps.textureAnisotropicFilterExtension = null;
  94835. _this._caps.maxAnisotropy = 0;
  94836. _this._caps.uintIndices = false;
  94837. _this._caps.fragmentDepthSupported = false;
  94838. _this._caps.highPrecisionShaderSupported = true;
  94839. _this._caps.colorBufferFloat = false;
  94840. _this._caps.textureFloat = false;
  94841. _this._caps.textureFloatLinearFiltering = false;
  94842. _this._caps.textureFloatRender = false;
  94843. _this._caps.textureHalfFloat = false;
  94844. _this._caps.textureHalfFloatLinearFiltering = false;
  94845. _this._caps.textureHalfFloatRender = false;
  94846. _this._caps.textureLOD = false;
  94847. _this._caps.drawBuffersExtension = false;
  94848. _this._caps.depthTextureExtension = false;
  94849. _this._caps.vertexArrayObject = false;
  94850. _this._caps.instancedArrays = false;
  94851. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94852. // Wrappers
  94853. if (typeof URL === "undefined") {
  94854. URL = {
  94855. createObjectURL: function () { },
  94856. revokeObjectURL: function () { }
  94857. };
  94858. }
  94859. if (typeof Blob === "undefined") {
  94860. Blob = function () { };
  94861. }
  94862. return _this;
  94863. }
  94864. NullEngine.prototype.isDeterministicLockStep = function () {
  94865. return this._options.deterministicLockstep;
  94866. };
  94867. NullEngine.prototype.getLockstepMaxSteps = function () {
  94868. return this._options.lockstepMaxSteps;
  94869. };
  94870. NullEngine.prototype.getHardwareScalingLevel = function () {
  94871. return 1.0;
  94872. };
  94873. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94874. return {
  94875. capacity: 0,
  94876. references: 1,
  94877. is32Bits: false
  94878. };
  94879. };
  94880. NullEngine.prototype.createIndexBuffer = function (indices) {
  94881. return {
  94882. capacity: 0,
  94883. references: 1,
  94884. is32Bits: false
  94885. };
  94886. };
  94887. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94888. if (stencil === void 0) { stencil = false; }
  94889. };
  94890. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94891. if (useScreen === void 0) { useScreen = false; }
  94892. if (!useScreen && this._currentRenderTarget) {
  94893. return this._currentRenderTarget.width;
  94894. }
  94895. return this._options.renderWidth;
  94896. };
  94897. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94898. if (useScreen === void 0) { useScreen = false; }
  94899. if (!useScreen && this._currentRenderTarget) {
  94900. return this._currentRenderTarget.height;
  94901. }
  94902. return this._options.renderHeight;
  94903. };
  94904. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94905. this._cachedViewport = viewport;
  94906. };
  94907. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94908. return {
  94909. transformFeedback: null,
  94910. __SPECTOR_rebuildProgram: null
  94911. };
  94912. };
  94913. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94914. return [];
  94915. };
  94916. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94917. return [];
  94918. };
  94919. NullEngine.prototype.bindSamplers = function (effect) {
  94920. this._currentEffect = null;
  94921. };
  94922. NullEngine.prototype.enableEffect = function (effect) {
  94923. this._currentEffect = effect;
  94924. if (effect.onBind) {
  94925. effect.onBind(effect);
  94926. }
  94927. effect.onBindObservable.notifyObservers(effect);
  94928. };
  94929. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94930. if (zOffset === void 0) { zOffset = 0; }
  94931. if (reverseSide === void 0) { reverseSide = false; }
  94932. };
  94933. NullEngine.prototype.setIntArray = function (uniform, array) {
  94934. };
  94935. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94936. };
  94937. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94938. };
  94939. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94940. };
  94941. NullEngine.prototype.setFloatArray = function (uniform, array) {
  94942. };
  94943. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  94944. };
  94945. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  94946. };
  94947. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  94948. };
  94949. NullEngine.prototype.setArray = function (uniform, array) {
  94950. };
  94951. NullEngine.prototype.setArray2 = function (uniform, array) {
  94952. };
  94953. NullEngine.prototype.setArray3 = function (uniform, array) {
  94954. };
  94955. NullEngine.prototype.setArray4 = function (uniform, array) {
  94956. };
  94957. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  94958. };
  94959. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  94960. };
  94961. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  94962. };
  94963. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  94964. };
  94965. NullEngine.prototype.setFloat = function (uniform, value) {
  94966. };
  94967. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  94968. };
  94969. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  94970. };
  94971. NullEngine.prototype.setBool = function (uniform, bool) {
  94972. };
  94973. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  94974. };
  94975. NullEngine.prototype.setColor3 = function (uniform, color3) {
  94976. };
  94977. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  94978. };
  94979. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  94980. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  94981. if (this._alphaMode === mode) {
  94982. return;
  94983. }
  94984. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  94985. if (!noDepthWriteChange) {
  94986. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  94987. }
  94988. this._alphaMode = mode;
  94989. };
  94990. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  94991. };
  94992. NullEngine.prototype.wipeCaches = function (bruteForce) {
  94993. if (this.preventCacheWipeBetweenFrames) {
  94994. return;
  94995. }
  94996. this.resetTextureCache();
  94997. this._currentEffect = null;
  94998. if (bruteForce) {
  94999. this._currentProgram = null;
  95000. this._stencilState.reset();
  95001. this._depthCullingState.reset();
  95002. this._alphaState.reset();
  95003. }
  95004. this._cachedVertexBuffers = null;
  95005. this._cachedIndexBuffer = null;
  95006. this._cachedEffectForVertexBuffers = null;
  95007. };
  95008. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95009. };
  95010. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95011. };
  95012. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95013. };
  95014. NullEngine.prototype._createTexture = function () {
  95015. return {};
  95016. };
  95017. NullEngine.prototype._releaseTexture = function (texture) {
  95018. };
  95019. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95021. if (onLoad === void 0) { onLoad = null; }
  95022. if (onError === void 0) { onError = null; }
  95023. if (buffer === void 0) { buffer = null; }
  95024. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95025. var url = String(urlArg);
  95026. texture.url = url;
  95027. texture.generateMipMaps = !noMipmap;
  95028. texture.samplingMode = samplingMode;
  95029. texture.invertY = invertY;
  95030. texture.baseWidth = this._options.textureSize;
  95031. texture.baseHeight = this._options.textureSize;
  95032. texture.width = this._options.textureSize;
  95033. texture.height = this._options.textureSize;
  95034. if (format) {
  95035. texture.format = format;
  95036. }
  95037. texture.isReady = true;
  95038. if (onLoad) {
  95039. onLoad();
  95040. }
  95041. return texture;
  95042. };
  95043. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95044. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95045. if (options !== undefined && typeof options === "object") {
  95046. fullOptions.generateMipMaps = options.generateMipMaps;
  95047. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95048. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95049. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95050. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95051. }
  95052. else {
  95053. fullOptions.generateMipMaps = options;
  95054. fullOptions.generateDepthBuffer = true;
  95055. fullOptions.generateStencilBuffer = false;
  95056. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95057. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95058. }
  95059. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95060. var width = size.width || size;
  95061. var height = size.height || size;
  95062. texture._depthStencilBuffer = {};
  95063. texture._framebuffer = {};
  95064. texture.baseWidth = width;
  95065. texture.baseHeight = height;
  95066. texture.width = width;
  95067. texture.height = height;
  95068. texture.isReady = true;
  95069. texture.samples = 1;
  95070. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95071. texture.samplingMode = fullOptions.samplingMode;
  95072. texture.type = fullOptions.type;
  95073. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95074. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95075. return texture;
  95076. };
  95077. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95078. texture.samplingMode = samplingMode;
  95079. };
  95080. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95081. if (this._currentRenderTarget) {
  95082. this.unBindFramebuffer(this._currentRenderTarget);
  95083. }
  95084. this._currentRenderTarget = texture;
  95085. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95086. if (this._cachedViewport && !forceFullscreenViewport) {
  95087. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95088. }
  95089. };
  95090. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95091. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95092. this._currentRenderTarget = null;
  95093. if (onBeforeUnbind) {
  95094. if (texture._MSAAFramebuffer) {
  95095. this._currentFramebuffer = texture._framebuffer;
  95096. }
  95097. onBeforeUnbind();
  95098. }
  95099. this._currentFramebuffer = null;
  95100. };
  95101. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95102. var vbo = {
  95103. capacity: 1,
  95104. references: 1,
  95105. is32Bits: false
  95106. };
  95107. return vbo;
  95108. };
  95109. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95110. if (offset === void 0) { offset = 0; }
  95111. };
  95112. /**
  95113. * Updates a dynamic vertex buffer.
  95114. * @param vertexBuffer the vertex buffer to update
  95115. * @param data the data used to update the vertex buffer
  95116. * @param byteOffset the byte offset of the data (optional)
  95117. * @param byteLength the byte length of the data (optional)
  95118. */
  95119. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95120. };
  95121. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95122. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95123. this._boundTexturesCache[this._activeChannel] = texture;
  95124. }
  95125. };
  95126. NullEngine.prototype._bindTexture = function (channel, texture) {
  95127. if (channel < 0) {
  95128. return;
  95129. }
  95130. this._bindTextureDirectly(0, texture);
  95131. };
  95132. NullEngine.prototype._releaseBuffer = function (buffer) {
  95133. buffer.references--;
  95134. if (buffer.references === 0) {
  95135. return true;
  95136. }
  95137. return false;
  95138. };
  95139. return NullEngine;
  95140. }(BABYLON.Engine));
  95141. BABYLON.NullEngine = NullEngine;
  95142. })(BABYLON || (BABYLON = {}));
  95143. //# sourceMappingURL=babylon.nullEngine.js.map
  95144. var BABYLON;
  95145. (function (BABYLON) {
  95146. /**
  95147. * This class can be used to get instrumentation data from a Babylon engine
  95148. */
  95149. var EngineInstrumentation = /** @class */ (function () {
  95150. function EngineInstrumentation(engine) {
  95151. this.engine = engine;
  95152. this._captureGPUFrameTime = false;
  95153. this._gpuFrameTime = new BABYLON.PerfCounter();
  95154. this._captureShaderCompilationTime = false;
  95155. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95156. // Observers
  95157. this._onBeginFrameObserver = null;
  95158. this._onEndFrameObserver = null;
  95159. this._onBeforeShaderCompilationObserver = null;
  95160. this._onAfterShaderCompilationObserver = null;
  95161. }
  95162. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95163. // Properties
  95164. /**
  95165. * Gets the perf counter used for GPU frame time
  95166. */
  95167. get: function () {
  95168. return this._gpuFrameTime;
  95169. },
  95170. enumerable: true,
  95171. configurable: true
  95172. });
  95173. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95174. /**
  95175. * Gets the GPU frame time capture status
  95176. */
  95177. get: function () {
  95178. return this._captureGPUFrameTime;
  95179. },
  95180. /**
  95181. * Enable or disable the GPU frame time capture
  95182. */
  95183. set: function (value) {
  95184. var _this = this;
  95185. if (value === this._captureGPUFrameTime) {
  95186. return;
  95187. }
  95188. this._captureGPUFrameTime = value;
  95189. if (value) {
  95190. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95191. if (!_this._gpuFrameTimeToken) {
  95192. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95193. }
  95194. });
  95195. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95196. if (!_this._gpuFrameTimeToken) {
  95197. return;
  95198. }
  95199. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95200. if (time > -1) {
  95201. _this._gpuFrameTimeToken = null;
  95202. _this._gpuFrameTime.fetchNewFrame();
  95203. _this._gpuFrameTime.addCount(time, true);
  95204. }
  95205. });
  95206. }
  95207. else {
  95208. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95209. this._onBeginFrameObserver = null;
  95210. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95211. this._onEndFrameObserver = null;
  95212. }
  95213. },
  95214. enumerable: true,
  95215. configurable: true
  95216. });
  95217. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95218. /**
  95219. * Gets the perf counter used for shader compilation time
  95220. */
  95221. get: function () {
  95222. return this._shaderCompilationTime;
  95223. },
  95224. enumerable: true,
  95225. configurable: true
  95226. });
  95227. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95228. /**
  95229. * Gets the shader compilation time capture status
  95230. */
  95231. get: function () {
  95232. return this._captureShaderCompilationTime;
  95233. },
  95234. /**
  95235. * Enable or disable the shader compilation time capture
  95236. */
  95237. set: function (value) {
  95238. var _this = this;
  95239. if (value === this._captureShaderCompilationTime) {
  95240. return;
  95241. }
  95242. this._captureShaderCompilationTime = value;
  95243. if (value) {
  95244. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95245. _this._shaderCompilationTime.fetchNewFrame();
  95246. _this._shaderCompilationTime.beginMonitoring();
  95247. });
  95248. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95249. _this._shaderCompilationTime.endMonitoring();
  95250. });
  95251. }
  95252. else {
  95253. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95254. this._onBeforeShaderCompilationObserver = null;
  95255. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95256. this._onAfterShaderCompilationObserver = null;
  95257. }
  95258. },
  95259. enumerable: true,
  95260. configurable: true
  95261. });
  95262. EngineInstrumentation.prototype.dispose = function () {
  95263. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95264. this._onBeginFrameObserver = null;
  95265. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95266. this._onEndFrameObserver = null;
  95267. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95268. this._onBeforeShaderCompilationObserver = null;
  95269. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95270. this._onAfterShaderCompilationObserver = null;
  95271. this.engine = null;
  95272. };
  95273. return EngineInstrumentation;
  95274. }());
  95275. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95276. })(BABYLON || (BABYLON = {}));
  95277. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95278. var BABYLON;
  95279. (function (BABYLON) {
  95280. /**
  95281. * This class can be used to get instrumentation data from a Babylon engine
  95282. */
  95283. var SceneInstrumentation = /** @class */ (function () {
  95284. function SceneInstrumentation(scene) {
  95285. var _this = this;
  95286. this.scene = scene;
  95287. this._captureActiveMeshesEvaluationTime = false;
  95288. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95289. this._captureRenderTargetsRenderTime = false;
  95290. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95291. this._captureFrameTime = false;
  95292. this._frameTime = new BABYLON.PerfCounter();
  95293. this._captureRenderTime = false;
  95294. this._renderTime = new BABYLON.PerfCounter();
  95295. this._captureInterFrameTime = false;
  95296. this._interFrameTime = new BABYLON.PerfCounter();
  95297. this._captureParticlesRenderTime = false;
  95298. this._particlesRenderTime = new BABYLON.PerfCounter();
  95299. this._captureSpritesRenderTime = false;
  95300. this._spritesRenderTime = new BABYLON.PerfCounter();
  95301. this._capturePhysicsTime = false;
  95302. this._physicsTime = new BABYLON.PerfCounter();
  95303. this._captureAnimationsTime = false;
  95304. this._animationsTime = new BABYLON.PerfCounter();
  95305. // Observers
  95306. this._onBeforeActiveMeshesEvaluationObserver = null;
  95307. this._onAfterActiveMeshesEvaluationObserver = null;
  95308. this._onBeforeRenderTargetsRenderObserver = null;
  95309. this._onAfterRenderTargetsRenderObserver = null;
  95310. this._onAfterRenderObserver = null;
  95311. this._onBeforeDrawPhaseObserver = null;
  95312. this._onAfterDrawPhaseObserver = null;
  95313. this._onBeforeAnimationsObserver = null;
  95314. this._onBeforeParticlesRenderingObserver = null;
  95315. this._onAfterParticlesRenderingObserver = null;
  95316. this._onBeforeSpritesRenderingObserver = null;
  95317. this._onAfterSpritesRenderingObserver = null;
  95318. this._onBeforePhysicsObserver = null;
  95319. this._onAfterPhysicsObserver = null;
  95320. this._onAfterAnimationsObserver = null;
  95321. // Before render
  95322. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95323. if (_this._captureActiveMeshesEvaluationTime) {
  95324. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95325. }
  95326. if (_this._captureRenderTargetsRenderTime) {
  95327. _this._renderTargetsRenderTime.fetchNewFrame();
  95328. }
  95329. if (_this._captureFrameTime) {
  95330. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95331. _this._frameTime.beginMonitoring();
  95332. }
  95333. if (_this._captureInterFrameTime) {
  95334. _this._interFrameTime.endMonitoring();
  95335. }
  95336. if (_this._captureParticlesRenderTime) {
  95337. _this._particlesRenderTime.fetchNewFrame();
  95338. }
  95339. if (_this._captureSpritesRenderTime) {
  95340. _this._spritesRenderTime.fetchNewFrame();
  95341. }
  95342. if (_this._captureAnimationsTime) {
  95343. _this._animationsTime.beginMonitoring();
  95344. }
  95345. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95346. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95347. });
  95348. // After render
  95349. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95350. if (_this._captureFrameTime) {
  95351. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95352. _this._frameTime.endMonitoring();
  95353. }
  95354. if (_this._captureRenderTime) {
  95355. _this._renderTime.endMonitoring(false);
  95356. }
  95357. if (_this._captureInterFrameTime) {
  95358. _this._interFrameTime.beginMonitoring();
  95359. }
  95360. });
  95361. }
  95362. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95363. // Properties
  95364. /**
  95365. * Gets the perf counter used for active meshes evaluation time
  95366. */
  95367. get: function () {
  95368. return this._activeMeshesEvaluationTime;
  95369. },
  95370. enumerable: true,
  95371. configurable: true
  95372. });
  95373. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95374. /**
  95375. * Gets the active meshes evaluation time capture status
  95376. */
  95377. get: function () {
  95378. return this._captureActiveMeshesEvaluationTime;
  95379. },
  95380. /**
  95381. * Enable or disable the active meshes evaluation time capture
  95382. */
  95383. set: function (value) {
  95384. var _this = this;
  95385. if (value === this._captureActiveMeshesEvaluationTime) {
  95386. return;
  95387. }
  95388. this._captureActiveMeshesEvaluationTime = value;
  95389. if (value) {
  95390. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95391. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95392. _this._activeMeshesEvaluationTime.beginMonitoring();
  95393. });
  95394. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95395. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95396. _this._activeMeshesEvaluationTime.endMonitoring();
  95397. });
  95398. }
  95399. else {
  95400. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95401. this._onBeforeActiveMeshesEvaluationObserver = null;
  95402. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95403. this._onAfterActiveMeshesEvaluationObserver = null;
  95404. }
  95405. },
  95406. enumerable: true,
  95407. configurable: true
  95408. });
  95409. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95410. /**
  95411. * Gets the perf counter used for render targets render time
  95412. */
  95413. get: function () {
  95414. return this._renderTargetsRenderTime;
  95415. },
  95416. enumerable: true,
  95417. configurable: true
  95418. });
  95419. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95420. /**
  95421. * Gets the render targets render time capture status
  95422. */
  95423. get: function () {
  95424. return this._captureRenderTargetsRenderTime;
  95425. },
  95426. /**
  95427. * Enable or disable the render targets render time capture
  95428. */
  95429. set: function (value) {
  95430. var _this = this;
  95431. if (value === this._captureRenderTargetsRenderTime) {
  95432. return;
  95433. }
  95434. this._captureRenderTargetsRenderTime = value;
  95435. if (value) {
  95436. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95437. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95438. _this._renderTargetsRenderTime.beginMonitoring();
  95439. });
  95440. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95441. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95442. _this._renderTargetsRenderTime.endMonitoring(false);
  95443. });
  95444. }
  95445. else {
  95446. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95447. this._onBeforeRenderTargetsRenderObserver = null;
  95448. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95449. this._onAfterRenderTargetsRenderObserver = null;
  95450. }
  95451. },
  95452. enumerable: true,
  95453. configurable: true
  95454. });
  95455. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95456. /**
  95457. * Gets the perf counter used for particles render time
  95458. */
  95459. get: function () {
  95460. return this._particlesRenderTime;
  95461. },
  95462. enumerable: true,
  95463. configurable: true
  95464. });
  95465. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95466. /**
  95467. * Gets the particles render time capture status
  95468. */
  95469. get: function () {
  95470. return this._captureParticlesRenderTime;
  95471. },
  95472. /**
  95473. * Enable or disable the particles render time capture
  95474. */
  95475. set: function (value) {
  95476. var _this = this;
  95477. if (value === this._captureParticlesRenderTime) {
  95478. return;
  95479. }
  95480. this._captureParticlesRenderTime = value;
  95481. if (value) {
  95482. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95483. BABYLON.Tools.StartPerformanceCounter("Particles");
  95484. _this._particlesRenderTime.beginMonitoring();
  95485. });
  95486. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95487. BABYLON.Tools.EndPerformanceCounter("Particles");
  95488. _this._particlesRenderTime.endMonitoring(false);
  95489. });
  95490. }
  95491. else {
  95492. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95493. this._onBeforeParticlesRenderingObserver = null;
  95494. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95495. this._onAfterParticlesRenderingObserver = null;
  95496. }
  95497. },
  95498. enumerable: true,
  95499. configurable: true
  95500. });
  95501. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95502. /**
  95503. * Gets the perf counter used for sprites render time
  95504. */
  95505. get: function () {
  95506. return this._spritesRenderTime;
  95507. },
  95508. enumerable: true,
  95509. configurable: true
  95510. });
  95511. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95512. /**
  95513. * Gets the sprites render time capture status
  95514. */
  95515. get: function () {
  95516. return this._captureSpritesRenderTime;
  95517. },
  95518. /**
  95519. * Enable or disable the sprites render time capture
  95520. */
  95521. set: function (value) {
  95522. var _this = this;
  95523. if (value === this._captureSpritesRenderTime) {
  95524. return;
  95525. }
  95526. this._captureSpritesRenderTime = value;
  95527. if (value) {
  95528. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95529. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95530. _this._spritesRenderTime.beginMonitoring();
  95531. });
  95532. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95533. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95534. _this._spritesRenderTime.endMonitoring(false);
  95535. });
  95536. }
  95537. else {
  95538. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95539. this._onBeforeSpritesRenderingObserver = null;
  95540. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95541. this._onAfterSpritesRenderingObserver = null;
  95542. }
  95543. },
  95544. enumerable: true,
  95545. configurable: true
  95546. });
  95547. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95548. /**
  95549. * Gets the perf counter used for physics time
  95550. */
  95551. get: function () {
  95552. return this._physicsTime;
  95553. },
  95554. enumerable: true,
  95555. configurable: true
  95556. });
  95557. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95558. /**
  95559. * Gets the physics time capture status
  95560. */
  95561. get: function () {
  95562. return this._capturePhysicsTime;
  95563. },
  95564. /**
  95565. * Enable or disable the physics time capture
  95566. */
  95567. set: function (value) {
  95568. var _this = this;
  95569. if (value === this._capturePhysicsTime) {
  95570. return;
  95571. }
  95572. this._capturePhysicsTime = value;
  95573. if (value) {
  95574. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95575. BABYLON.Tools.StartPerformanceCounter("Physics");
  95576. _this._physicsTime.beginMonitoring();
  95577. });
  95578. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95579. BABYLON.Tools.EndPerformanceCounter("Physics");
  95580. _this._physicsTime.endMonitoring();
  95581. });
  95582. }
  95583. else {
  95584. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95585. this._onBeforePhysicsObserver = null;
  95586. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95587. this._onAfterPhysicsObserver = null;
  95588. }
  95589. },
  95590. enumerable: true,
  95591. configurable: true
  95592. });
  95593. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95594. /**
  95595. * Gets the perf counter used for animations time
  95596. */
  95597. get: function () {
  95598. return this._animationsTime;
  95599. },
  95600. enumerable: true,
  95601. configurable: true
  95602. });
  95603. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95604. /**
  95605. * Gets the animations time capture status
  95606. */
  95607. get: function () {
  95608. return this._captureAnimationsTime;
  95609. },
  95610. /**
  95611. * Enable or disable the animations time capture
  95612. */
  95613. set: function (value) {
  95614. var _this = this;
  95615. if (value === this._captureAnimationsTime) {
  95616. return;
  95617. }
  95618. this._captureAnimationsTime = value;
  95619. if (value) {
  95620. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95621. _this._animationsTime.endMonitoring();
  95622. });
  95623. }
  95624. else {
  95625. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95626. this._onAfterAnimationsObserver = null;
  95627. }
  95628. },
  95629. enumerable: true,
  95630. configurable: true
  95631. });
  95632. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95633. /**
  95634. * Gets the perf counter used for frame time capture
  95635. */
  95636. get: function () {
  95637. return this._frameTime;
  95638. },
  95639. enumerable: true,
  95640. configurable: true
  95641. });
  95642. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95643. /**
  95644. * Gets the frame time capture status
  95645. */
  95646. get: function () {
  95647. return this._captureFrameTime;
  95648. },
  95649. /**
  95650. * Enable or disable the frame time capture
  95651. */
  95652. set: function (value) {
  95653. this._captureFrameTime = value;
  95654. },
  95655. enumerable: true,
  95656. configurable: true
  95657. });
  95658. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95659. /**
  95660. * Gets the perf counter used for inter-frames time capture
  95661. */
  95662. get: function () {
  95663. return this._interFrameTime;
  95664. },
  95665. enumerable: true,
  95666. configurable: true
  95667. });
  95668. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95669. /**
  95670. * Gets the inter-frames time capture status
  95671. */
  95672. get: function () {
  95673. return this._captureInterFrameTime;
  95674. },
  95675. /**
  95676. * Enable or disable the inter-frames time capture
  95677. */
  95678. set: function (value) {
  95679. this._captureInterFrameTime = value;
  95680. },
  95681. enumerable: true,
  95682. configurable: true
  95683. });
  95684. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95685. /**
  95686. * Gets the perf counter used for render time capture
  95687. */
  95688. get: function () {
  95689. return this._renderTime;
  95690. },
  95691. enumerable: true,
  95692. configurable: true
  95693. });
  95694. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95695. /**
  95696. * Gets the render time capture status
  95697. */
  95698. get: function () {
  95699. return this._captureRenderTime;
  95700. },
  95701. /**
  95702. * Enable or disable the render time capture
  95703. */
  95704. set: function (value) {
  95705. var _this = this;
  95706. if (value === this._captureRenderTime) {
  95707. return;
  95708. }
  95709. this._captureRenderTime = value;
  95710. if (value) {
  95711. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95712. _this._renderTime.beginMonitoring();
  95713. BABYLON.Tools.StartPerformanceCounter("Main render");
  95714. });
  95715. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95716. _this._renderTime.endMonitoring(false);
  95717. BABYLON.Tools.EndPerformanceCounter("Main render");
  95718. });
  95719. }
  95720. else {
  95721. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95722. this._onBeforeDrawPhaseObserver = null;
  95723. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95724. this._onAfterDrawPhaseObserver = null;
  95725. }
  95726. },
  95727. enumerable: true,
  95728. configurable: true
  95729. });
  95730. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95731. /**
  95732. * Gets the perf counter used for draw calls
  95733. */
  95734. get: function () {
  95735. return this.scene.getEngine()._drawCalls;
  95736. },
  95737. enumerable: true,
  95738. configurable: true
  95739. });
  95740. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95741. /**
  95742. * Gets the perf counter used for texture collisions
  95743. */
  95744. get: function () {
  95745. return this.scene.getEngine()._textureCollisions;
  95746. },
  95747. enumerable: true,
  95748. configurable: true
  95749. });
  95750. SceneInstrumentation.prototype.dispose = function () {
  95751. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95752. this._onAfterRenderObserver = null;
  95753. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95754. this._onBeforeActiveMeshesEvaluationObserver = null;
  95755. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95756. this._onAfterActiveMeshesEvaluationObserver = null;
  95757. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95758. this._onBeforeRenderTargetsRenderObserver = null;
  95759. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95760. this._onAfterRenderTargetsRenderObserver = null;
  95761. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95762. this._onBeforeAnimationsObserver = null;
  95763. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95764. this._onBeforeParticlesRenderingObserver = null;
  95765. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95766. this._onAfterParticlesRenderingObserver = null;
  95767. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95768. this._onBeforeSpritesRenderingObserver = null;
  95769. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95770. this._onAfterSpritesRenderingObserver = null;
  95771. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95772. this._onBeforeDrawPhaseObserver = null;
  95773. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95774. this._onAfterDrawPhaseObserver = null;
  95775. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95776. this._onBeforePhysicsObserver = null;
  95777. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95778. this._onAfterPhysicsObserver = null;
  95779. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95780. this._onAfterAnimationsObserver = null;
  95781. this.scene = null;
  95782. };
  95783. return SceneInstrumentation;
  95784. }());
  95785. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95786. })(BABYLON || (BABYLON = {}));
  95787. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95788. var BABYLON;
  95789. (function (BABYLON) {
  95790. /**
  95791. * @hidden
  95792. **/
  95793. var _TimeToken = /** @class */ (function () {
  95794. function _TimeToken() {
  95795. this._timeElapsedQueryEnded = false;
  95796. }
  95797. return _TimeToken;
  95798. }());
  95799. BABYLON._TimeToken = _TimeToken;
  95800. })(BABYLON || (BABYLON = {}));
  95801. //# sourceMappingURL=babylon.timeToken.js.map
  95802. var BABYLON;
  95803. (function (BABYLON) {
  95804. /**
  95805. * Background material defines definition.
  95806. * @hidden Mainly internal Use
  95807. */
  95808. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95809. __extends(BackgroundMaterialDefines, _super);
  95810. /**
  95811. * Constructor of the defines.
  95812. */
  95813. function BackgroundMaterialDefines() {
  95814. var _this = _super.call(this) || this;
  95815. /**
  95816. * True if the diffuse texture is in use.
  95817. */
  95818. _this.DIFFUSE = false;
  95819. /**
  95820. * The direct UV channel to use.
  95821. */
  95822. _this.DIFFUSEDIRECTUV = 0;
  95823. /**
  95824. * True if the diffuse texture is in gamma space.
  95825. */
  95826. _this.GAMMADIFFUSE = false;
  95827. /**
  95828. * True if the diffuse texture has opacity in the alpha channel.
  95829. */
  95830. _this.DIFFUSEHASALPHA = false;
  95831. /**
  95832. * True if you want the material to fade to transparent at grazing angle.
  95833. */
  95834. _this.OPACITYFRESNEL = false;
  95835. /**
  95836. * True if an extra blur needs to be added in the reflection.
  95837. */
  95838. _this.REFLECTIONBLUR = false;
  95839. /**
  95840. * True if you want the material to fade to reflection at grazing angle.
  95841. */
  95842. _this.REFLECTIONFRESNEL = false;
  95843. /**
  95844. * True if you want the material to falloff as far as you move away from the scene center.
  95845. */
  95846. _this.REFLECTIONFALLOFF = false;
  95847. /**
  95848. * False if the current Webgl implementation does not support the texture lod extension.
  95849. */
  95850. _this.TEXTURELODSUPPORT = false;
  95851. /**
  95852. * True to ensure the data are premultiplied.
  95853. */
  95854. _this.PREMULTIPLYALPHA = false;
  95855. /**
  95856. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95857. */
  95858. _this.USERGBCOLOR = false;
  95859. /**
  95860. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95861. * stays aligned with the desired configuration.
  95862. */
  95863. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95864. /**
  95865. * True to add noise in order to reduce the banding effect.
  95866. */
  95867. _this.NOISE = false;
  95868. /**
  95869. * is the reflection texture in BGR color scheme?
  95870. * Mainly used to solve a bug in ios10 video tag
  95871. */
  95872. _this.REFLECTIONBGR = false;
  95873. _this.IMAGEPROCESSING = false;
  95874. _this.VIGNETTE = false;
  95875. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95876. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95877. _this.TONEMAPPING = false;
  95878. _this.CONTRAST = false;
  95879. _this.COLORCURVES = false;
  95880. _this.COLORGRADING = false;
  95881. _this.COLORGRADING3D = false;
  95882. _this.SAMPLER3DGREENDEPTH = false;
  95883. _this.SAMPLER3DBGRMAP = false;
  95884. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95885. _this.EXPOSURE = false;
  95886. // Reflection.
  95887. _this.REFLECTION = false;
  95888. _this.REFLECTIONMAP_3D = false;
  95889. _this.REFLECTIONMAP_SPHERICAL = false;
  95890. _this.REFLECTIONMAP_PLANAR = false;
  95891. _this.REFLECTIONMAP_CUBIC = false;
  95892. _this.REFLECTIONMAP_PROJECTION = false;
  95893. _this.REFLECTIONMAP_SKYBOX = false;
  95894. _this.REFLECTIONMAP_EXPLICIT = false;
  95895. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95896. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95897. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95898. _this.INVERTCUBICMAP = false;
  95899. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95900. _this.LODINREFLECTIONALPHA = false;
  95901. _this.GAMMAREFLECTION = false;
  95902. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95903. // Default BJS.
  95904. _this.MAINUV1 = false;
  95905. _this.MAINUV2 = false;
  95906. _this.UV1 = false;
  95907. _this.UV2 = false;
  95908. _this.CLIPPLANE = false;
  95909. _this.POINTSIZE = false;
  95910. _this.FOG = false;
  95911. _this.NORMAL = false;
  95912. _this.NUM_BONE_INFLUENCERS = 0;
  95913. _this.BonesPerMesh = 0;
  95914. _this.INSTANCES = false;
  95915. _this.SHADOWFLOAT = false;
  95916. _this.rebuild();
  95917. return _this;
  95918. }
  95919. return BackgroundMaterialDefines;
  95920. }(BABYLON.MaterialDefines));
  95921. /**
  95922. * Background material used to create an efficient environement around your scene.
  95923. */
  95924. var BackgroundMaterial = /** @class */ (function (_super) {
  95925. __extends(BackgroundMaterial, _super);
  95926. /**
  95927. * Instantiates a Background Material in the given scene
  95928. * @param name The friendly name of the material
  95929. * @param scene The scene to add the material to
  95930. */
  95931. function BackgroundMaterial(name, scene) {
  95932. var _this = _super.call(this, name, scene) || this;
  95933. /**
  95934. * Key light Color (multiply against the environement texture)
  95935. */
  95936. _this.primaryColor = BABYLON.Color3.White();
  95937. _this._primaryColorShadowLevel = 0;
  95938. _this._primaryColorHighlightLevel = 0;
  95939. /**
  95940. * Reflection Texture used in the material.
  95941. * Should be author in a specific way for the best result (refer to the documentation).
  95942. */
  95943. _this.reflectionTexture = null;
  95944. /**
  95945. * Reflection Texture level of blur.
  95946. *
  95947. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  95948. * texture twice.
  95949. */
  95950. _this.reflectionBlur = 0;
  95951. /**
  95952. * Diffuse Texture used in the material.
  95953. * Should be author in a specific way for the best result (refer to the documentation).
  95954. */
  95955. _this.diffuseTexture = null;
  95956. _this._shadowLights = null;
  95957. /**
  95958. * Specify the list of lights casting shadow on the material.
  95959. * All scene shadow lights will be included if null.
  95960. */
  95961. _this.shadowLights = null;
  95962. /**
  95963. * Helps adjusting the shadow to a softer level if required.
  95964. * 0 means black shadows and 1 means no shadows.
  95965. */
  95966. _this.shadowLevel = 0;
  95967. /**
  95968. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  95969. * It is usually zero but might be interesting to modify according to your setup.
  95970. */
  95971. _this.sceneCenter = BABYLON.Vector3.Zero();
  95972. /**
  95973. * This helps specifying that the material is falling off to the sky box at grazing angle.
  95974. * This helps ensuring a nice transition when the camera goes under the ground.
  95975. */
  95976. _this.opacityFresnel = true;
  95977. /**
  95978. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  95979. * This helps adding a mirror texture on the ground.
  95980. */
  95981. _this.reflectionFresnel = false;
  95982. /**
  95983. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  95984. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  95985. */
  95986. _this.reflectionFalloffDistance = 0.0;
  95987. /**
  95988. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  95989. */
  95990. _this.reflectionAmount = 1.0;
  95991. /**
  95992. * This specifies the weight of the reflection at grazing angle.
  95993. */
  95994. _this.reflectionReflectance0 = 0.05;
  95995. /**
  95996. * This specifies the weight of the reflection at a perpendicular point of view.
  95997. */
  95998. _this.reflectionReflectance90 = 0.5;
  95999. /**
  96000. * Helps to directly use the maps channels instead of their level.
  96001. */
  96002. _this.useRGBColor = true;
  96003. /**
  96004. * This helps reducing the banding effect that could occur on the background.
  96005. */
  96006. _this.enableNoise = false;
  96007. _this._fovMultiplier = 1.0;
  96008. /**
  96009. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96010. */
  96011. _this.useEquirectangularFOV = false;
  96012. _this._maxSimultaneousLights = 4;
  96013. /**
  96014. * Number of Simultaneous lights allowed on the material.
  96015. */
  96016. _this.maxSimultaneousLights = 4;
  96017. /**
  96018. * Keep track of the image processing observer to allow dispose and replace.
  96019. */
  96020. _this._imageProcessingObserver = null;
  96021. /**
  96022. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96023. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96024. */
  96025. _this.switchToBGR = false;
  96026. // Temp values kept as cache in the material.
  96027. _this._renderTargets = new BABYLON.SmartArray(16);
  96028. _this._reflectionControls = BABYLON.Vector4.Zero();
  96029. _this._white = BABYLON.Color3.White();
  96030. _this._primaryShadowColor = BABYLON.Color3.Black();
  96031. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96032. // Setup the default processing configuration to the scene.
  96033. _this._attachImageProcessingConfiguration(null);
  96034. _this.getRenderTargetTextures = function () {
  96035. _this._renderTargets.reset();
  96036. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96037. _this._renderTargets.push(_this._diffuseTexture);
  96038. }
  96039. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96040. _this._renderTargets.push(_this._reflectionTexture);
  96041. }
  96042. return _this._renderTargets;
  96043. };
  96044. return _this;
  96045. }
  96046. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96047. /**
  96048. * Experimental Internal Use Only.
  96049. *
  96050. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96051. * This acts as a helper to set the primary color to a more "human friendly" value.
  96052. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96053. * output color as close as possible from the chosen value.
  96054. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96055. * part of lighting setup.)
  96056. */
  96057. get: function () {
  96058. return this.__perceptualColor;
  96059. },
  96060. set: function (value) {
  96061. this.__perceptualColor = value;
  96062. this._computePrimaryColorFromPerceptualColor();
  96063. this._markAllSubMeshesAsLightsDirty();
  96064. },
  96065. enumerable: true,
  96066. configurable: true
  96067. });
  96068. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96069. /**
  96070. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96071. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96072. */
  96073. get: function () {
  96074. return this._primaryColorShadowLevel;
  96075. },
  96076. set: function (value) {
  96077. this._primaryColorShadowLevel = value;
  96078. this._computePrimaryColors();
  96079. this._markAllSubMeshesAsLightsDirty();
  96080. },
  96081. enumerable: true,
  96082. configurable: true
  96083. });
  96084. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96085. /**
  96086. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96087. * The primary color is used at the level chosen to define what the white area would look.
  96088. */
  96089. get: function () {
  96090. return this._primaryColorHighlightLevel;
  96091. },
  96092. set: function (value) {
  96093. this._primaryColorHighlightLevel = value;
  96094. this._computePrimaryColors();
  96095. this._markAllSubMeshesAsLightsDirty();
  96096. },
  96097. enumerable: true,
  96098. configurable: true
  96099. });
  96100. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96101. /**
  96102. * Sets the reflection reflectance fresnel values according to the default standard
  96103. * empirically know to work well :-)
  96104. */
  96105. set: function (value) {
  96106. var reflectionWeight = value;
  96107. if (reflectionWeight < 0.5) {
  96108. reflectionWeight = reflectionWeight * 2.0;
  96109. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96110. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96111. }
  96112. else {
  96113. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96114. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96115. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96116. }
  96117. },
  96118. enumerable: true,
  96119. configurable: true
  96120. });
  96121. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96122. /**
  96123. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96124. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96125. * Recommended to be keep at 1.0 except for special cases.
  96126. */
  96127. get: function () {
  96128. return this._fovMultiplier;
  96129. },
  96130. set: function (value) {
  96131. if (isNaN(value)) {
  96132. value = 1.0;
  96133. }
  96134. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96135. },
  96136. enumerable: true,
  96137. configurable: true
  96138. });
  96139. /**
  96140. * Attaches a new image processing configuration to the PBR Material.
  96141. * @param configuration (if null the scene configuration will be use)
  96142. */
  96143. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96144. var _this = this;
  96145. if (configuration === this._imageProcessingConfiguration) {
  96146. return;
  96147. }
  96148. // Detaches observer.
  96149. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96150. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96151. }
  96152. // Pick the scene configuration if needed.
  96153. if (!configuration) {
  96154. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96155. }
  96156. else {
  96157. this._imageProcessingConfiguration = configuration;
  96158. }
  96159. // Attaches observer.
  96160. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96161. _this._computePrimaryColorFromPerceptualColor();
  96162. _this._markAllSubMeshesAsImageProcessingDirty();
  96163. });
  96164. };
  96165. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96166. /**
  96167. * Gets the image processing configuration used either in this material.
  96168. */
  96169. get: function () {
  96170. return this._imageProcessingConfiguration;
  96171. },
  96172. /**
  96173. * Sets the Default image processing configuration used either in the this material.
  96174. *
  96175. * If sets to null, the scene one is in use.
  96176. */
  96177. set: function (value) {
  96178. this._attachImageProcessingConfiguration(value);
  96179. // Ensure the effect will be rebuilt.
  96180. this._markAllSubMeshesAsTexturesDirty();
  96181. },
  96182. enumerable: true,
  96183. configurable: true
  96184. });
  96185. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96186. /**
  96187. * Gets wether the color curves effect is enabled.
  96188. */
  96189. get: function () {
  96190. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96191. },
  96192. /**
  96193. * Sets wether the color curves effect is enabled.
  96194. */
  96195. set: function (value) {
  96196. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96197. },
  96198. enumerable: true,
  96199. configurable: true
  96200. });
  96201. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96202. /**
  96203. * Gets wether the color grading effect is enabled.
  96204. */
  96205. get: function () {
  96206. return this.imageProcessingConfiguration.colorGradingEnabled;
  96207. },
  96208. /**
  96209. * Gets wether the color grading effect is enabled.
  96210. */
  96211. set: function (value) {
  96212. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96213. },
  96214. enumerable: true,
  96215. configurable: true
  96216. });
  96217. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96218. /**
  96219. * Gets wether tonemapping is enabled or not.
  96220. */
  96221. get: function () {
  96222. return this._imageProcessingConfiguration.toneMappingEnabled;
  96223. },
  96224. /**
  96225. * Sets wether tonemapping is enabled or not
  96226. */
  96227. set: function (value) {
  96228. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96229. },
  96230. enumerable: true,
  96231. configurable: true
  96232. });
  96233. ;
  96234. ;
  96235. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96236. /**
  96237. * The camera exposure used on this material.
  96238. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96239. * This corresponds to a photographic exposure.
  96240. */
  96241. get: function () {
  96242. return this._imageProcessingConfiguration.exposure;
  96243. },
  96244. /**
  96245. * The camera exposure used on this material.
  96246. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96247. * This corresponds to a photographic exposure.
  96248. */
  96249. set: function (value) {
  96250. this._imageProcessingConfiguration.exposure = value;
  96251. },
  96252. enumerable: true,
  96253. configurable: true
  96254. });
  96255. ;
  96256. ;
  96257. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96258. /**
  96259. * Gets The camera contrast used on this material.
  96260. */
  96261. get: function () {
  96262. return this._imageProcessingConfiguration.contrast;
  96263. },
  96264. /**
  96265. * Sets The camera contrast used on this material.
  96266. */
  96267. set: function (value) {
  96268. this._imageProcessingConfiguration.contrast = value;
  96269. },
  96270. enumerable: true,
  96271. configurable: true
  96272. });
  96273. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96274. /**
  96275. * Gets the Color Grading 2D Lookup Texture.
  96276. */
  96277. get: function () {
  96278. return this._imageProcessingConfiguration.colorGradingTexture;
  96279. },
  96280. /**
  96281. * Sets the Color Grading 2D Lookup Texture.
  96282. */
  96283. set: function (value) {
  96284. this.imageProcessingConfiguration.colorGradingTexture = value;
  96285. },
  96286. enumerable: true,
  96287. configurable: true
  96288. });
  96289. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96290. /**
  96291. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96292. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96293. * 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;
  96294. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96295. */
  96296. get: function () {
  96297. return this.imageProcessingConfiguration.colorCurves;
  96298. },
  96299. /**
  96300. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96301. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96302. * 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;
  96303. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96304. */
  96305. set: function (value) {
  96306. this.imageProcessingConfiguration.colorCurves = value;
  96307. },
  96308. enumerable: true,
  96309. configurable: true
  96310. });
  96311. /**
  96312. * The entire material has been created in order to prevent overdraw.
  96313. * @returns false
  96314. */
  96315. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96316. return true;
  96317. };
  96318. /**
  96319. * The entire material has been created in order to prevent overdraw.
  96320. * @returns true if blending is enable
  96321. */
  96322. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96323. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96324. };
  96325. /**
  96326. * Checks wether the material is ready to be rendered for a given mesh.
  96327. * @param mesh The mesh to render
  96328. * @param subMesh The submesh to check against
  96329. * @param useInstances Specify wether or not the material is used with instances
  96330. * @returns true if all the dependencies are ready (Textures, Effects...)
  96331. */
  96332. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96333. var _this = this;
  96334. if (useInstances === void 0) { useInstances = false; }
  96335. if (subMesh.effect && this.isFrozen) {
  96336. if (this._wasPreviouslyReady) {
  96337. return true;
  96338. }
  96339. }
  96340. if (!subMesh._materialDefines) {
  96341. subMesh._materialDefines = new BackgroundMaterialDefines();
  96342. }
  96343. var scene = this.getScene();
  96344. var defines = subMesh._materialDefines;
  96345. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96346. if (defines._renderId === scene.getRenderId()) {
  96347. return true;
  96348. }
  96349. }
  96350. var engine = scene.getEngine();
  96351. // Lights
  96352. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96353. defines._needNormals = true;
  96354. // Textures
  96355. if (defines._areTexturesDirty) {
  96356. defines._needUVs = false;
  96357. if (scene.texturesEnabled) {
  96358. if (scene.getEngine().getCaps().textureLOD) {
  96359. defines.TEXTURELODSUPPORT = true;
  96360. }
  96361. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96362. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96363. return false;
  96364. }
  96365. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96366. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96367. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96368. defines.OPACITYFRESNEL = this._opacityFresnel;
  96369. }
  96370. else {
  96371. defines.DIFFUSE = false;
  96372. defines.DIFFUSEHASALPHA = false;
  96373. defines.GAMMADIFFUSE = false;
  96374. defines.OPACITYFRESNEL = false;
  96375. }
  96376. var reflectionTexture = this._reflectionTexture;
  96377. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96378. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96379. return false;
  96380. }
  96381. defines.REFLECTION = true;
  96382. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96383. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96384. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96385. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96386. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96387. defines.REFLECTIONBGR = this.switchToBGR;
  96388. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96389. defines.INVERTCUBICMAP = true;
  96390. }
  96391. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96392. switch (reflectionTexture.coordinatesMode) {
  96393. case BABYLON.Texture.EXPLICIT_MODE:
  96394. defines.REFLECTIONMAP_EXPLICIT = true;
  96395. break;
  96396. case BABYLON.Texture.PLANAR_MODE:
  96397. defines.REFLECTIONMAP_PLANAR = true;
  96398. break;
  96399. case BABYLON.Texture.PROJECTION_MODE:
  96400. defines.REFLECTIONMAP_PROJECTION = true;
  96401. break;
  96402. case BABYLON.Texture.SKYBOX_MODE:
  96403. defines.REFLECTIONMAP_SKYBOX = true;
  96404. break;
  96405. case BABYLON.Texture.SPHERICAL_MODE:
  96406. defines.REFLECTIONMAP_SPHERICAL = true;
  96407. break;
  96408. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96409. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96410. break;
  96411. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96412. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96413. break;
  96414. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96415. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96416. break;
  96417. case BABYLON.Texture.CUBIC_MODE:
  96418. case BABYLON.Texture.INVCUBIC_MODE:
  96419. default:
  96420. defines.REFLECTIONMAP_CUBIC = true;
  96421. break;
  96422. }
  96423. if (this.reflectionFresnel) {
  96424. defines.REFLECTIONFRESNEL = true;
  96425. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96426. this._reflectionControls.x = this.reflectionAmount;
  96427. this._reflectionControls.y = this.reflectionReflectance0;
  96428. this._reflectionControls.z = this.reflectionReflectance90;
  96429. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96430. }
  96431. else {
  96432. defines.REFLECTIONFRESNEL = false;
  96433. defines.REFLECTIONFALLOFF = false;
  96434. }
  96435. }
  96436. else {
  96437. defines.REFLECTION = false;
  96438. defines.REFLECTIONFRESNEL = false;
  96439. defines.REFLECTIONFALLOFF = false;
  96440. defines.REFLECTIONBLUR = false;
  96441. defines.REFLECTIONMAP_3D = false;
  96442. defines.REFLECTIONMAP_SPHERICAL = false;
  96443. defines.REFLECTIONMAP_PLANAR = false;
  96444. defines.REFLECTIONMAP_CUBIC = false;
  96445. defines.REFLECTIONMAP_PROJECTION = false;
  96446. defines.REFLECTIONMAP_SKYBOX = false;
  96447. defines.REFLECTIONMAP_EXPLICIT = false;
  96448. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96449. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96450. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96451. defines.INVERTCUBICMAP = false;
  96452. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96453. defines.LODINREFLECTIONALPHA = false;
  96454. defines.GAMMAREFLECTION = false;
  96455. }
  96456. }
  96457. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96458. defines.USERGBCOLOR = this._useRGBColor;
  96459. defines.NOISE = this._enableNoise;
  96460. }
  96461. if (defines._areLightsDirty) {
  96462. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96463. }
  96464. if (defines._areImageProcessingDirty) {
  96465. if (!this._imageProcessingConfiguration.isReady()) {
  96466. return false;
  96467. }
  96468. this._imageProcessingConfiguration.prepareDefines(defines);
  96469. }
  96470. // Misc.
  96471. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96472. // Values that need to be evaluated on every frame
  96473. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96474. // Attribs
  96475. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96476. if (mesh) {
  96477. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96478. mesh.createNormals(true);
  96479. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96480. }
  96481. }
  96482. }
  96483. // Get correct effect
  96484. if (defines.isDirty) {
  96485. defines.markAsProcessed();
  96486. scene.resetCachedMaterial();
  96487. // Fallbacks
  96488. var fallbacks = new BABYLON.EffectFallbacks();
  96489. if (defines.FOG) {
  96490. fallbacks.addFallback(0, "FOG");
  96491. }
  96492. if (defines.POINTSIZE) {
  96493. fallbacks.addFallback(1, "POINTSIZE");
  96494. }
  96495. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96496. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96497. fallbacks.addCPUSkinningFallback(0, mesh);
  96498. }
  96499. //Attributes
  96500. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96501. if (defines.NORMAL) {
  96502. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96503. }
  96504. if (defines.UV1) {
  96505. attribs.push(BABYLON.VertexBuffer.UVKind);
  96506. }
  96507. if (defines.UV2) {
  96508. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96509. }
  96510. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96511. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96512. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96513. "vFogInfos", "vFogColor", "pointSize",
  96514. "vClipPlane", "mBones",
  96515. "vPrimaryColor", "vPrimaryColorShadow",
  96516. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96517. "shadowLevel", "alpha",
  96518. "vBackgroundCenter", "vReflectionControl",
  96519. "vDiffuseInfos", "diffuseMatrix",
  96520. ];
  96521. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96522. var uniformBuffers = ["Material", "Scene"];
  96523. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96524. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96525. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96526. uniformsNames: uniforms,
  96527. uniformBuffersNames: uniformBuffers,
  96528. samplers: samplers,
  96529. defines: defines,
  96530. maxSimultaneousLights: this._maxSimultaneousLights
  96531. });
  96532. var onCompiled = function (effect) {
  96533. if (_this.onCompiled) {
  96534. _this.onCompiled(effect);
  96535. }
  96536. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96537. };
  96538. var join = defines.toString();
  96539. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96540. attributes: attribs,
  96541. uniformsNames: uniforms,
  96542. uniformBuffersNames: uniformBuffers,
  96543. samplers: samplers,
  96544. defines: join,
  96545. fallbacks: fallbacks,
  96546. onCompiled: onCompiled,
  96547. onError: this.onError,
  96548. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96549. }, engine), defines);
  96550. this.buildUniformLayout();
  96551. }
  96552. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96553. return false;
  96554. }
  96555. defines._renderId = scene.getRenderId();
  96556. this._wasPreviouslyReady = true;
  96557. return true;
  96558. };
  96559. /**
  96560. * Compute the primary color according to the chosen perceptual color.
  96561. */
  96562. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96563. if (!this.__perceptualColor) {
  96564. return;
  96565. }
  96566. this._primaryColor.copyFrom(this.__perceptualColor);
  96567. // Revert gamma space.
  96568. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96569. // Revert image processing configuration.
  96570. if (this._imageProcessingConfiguration) {
  96571. // Revert Exposure.
  96572. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96573. }
  96574. this._computePrimaryColors();
  96575. };
  96576. /**
  96577. * Compute the highlights and shadow colors according to their chosen levels.
  96578. */
  96579. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96580. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96581. return;
  96582. }
  96583. // Find the highlight color based on the configuration.
  96584. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96585. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96586. // Find the shadow color based on the configuration.
  96587. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96588. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96589. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96590. };
  96591. /**
  96592. * Build the uniform buffer used in the material.
  96593. */
  96594. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96595. // Order is important !
  96596. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96597. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96598. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96599. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96600. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96601. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96602. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96603. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96604. this._uniformBuffer.addUniform("pointSize", 1);
  96605. this._uniformBuffer.addUniform("shadowLevel", 1);
  96606. this._uniformBuffer.addUniform("alpha", 1);
  96607. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96608. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96609. this._uniformBuffer.create();
  96610. };
  96611. /**
  96612. * Unbind the material.
  96613. */
  96614. BackgroundMaterial.prototype.unbind = function () {
  96615. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96616. this._uniformBuffer.setTexture("diffuseSampler", null);
  96617. }
  96618. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96619. this._uniformBuffer.setTexture("reflectionSampler", null);
  96620. }
  96621. _super.prototype.unbind.call(this);
  96622. };
  96623. /**
  96624. * Bind only the world matrix to the material.
  96625. * @param world The world matrix to bind.
  96626. */
  96627. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96628. this._activeEffect.setMatrix("world", world);
  96629. };
  96630. /**
  96631. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96632. * @param world The world matrix to bind.
  96633. * @param subMesh The submesh to bind for.
  96634. */
  96635. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96636. var scene = this.getScene();
  96637. var defines = subMesh._materialDefines;
  96638. if (!defines) {
  96639. return;
  96640. }
  96641. var effect = subMesh.effect;
  96642. if (!effect) {
  96643. return;
  96644. }
  96645. this._activeEffect = effect;
  96646. // Matrices
  96647. this.bindOnlyWorldMatrix(world);
  96648. // Bones
  96649. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96650. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96651. if (mustRebind) {
  96652. this._uniformBuffer.bindToEffect(effect, "Material");
  96653. this.bindViewProjection(effect);
  96654. var reflectionTexture = this._reflectionTexture;
  96655. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96656. // Texture uniforms
  96657. if (scene.texturesEnabled) {
  96658. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96659. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96660. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96661. }
  96662. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96663. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96664. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96665. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96666. }
  96667. }
  96668. if (this.shadowLevel > 0) {
  96669. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96670. }
  96671. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96672. // Point size
  96673. if (this.pointsCloud) {
  96674. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96675. }
  96676. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96677. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96678. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96679. }
  96680. else {
  96681. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96682. }
  96683. }
  96684. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96685. // Textures
  96686. if (scene.texturesEnabled) {
  96687. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96688. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96689. }
  96690. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96691. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96692. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96693. }
  96694. else if (!defines.REFLECTIONBLUR) {
  96695. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96696. }
  96697. else {
  96698. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96699. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96700. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96701. }
  96702. if (defines.REFLECTIONFRESNEL) {
  96703. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96704. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96705. }
  96706. }
  96707. }
  96708. // Clip plane
  96709. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96710. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96711. }
  96712. if (mustRebind || !this.isFrozen) {
  96713. if (scene.lightsEnabled) {
  96714. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96715. }
  96716. // View
  96717. this.bindView(effect);
  96718. // Fog
  96719. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96720. // image processing
  96721. this._imageProcessingConfiguration.bind(this._activeEffect);
  96722. }
  96723. this._uniformBuffer.update();
  96724. this._afterBind(mesh);
  96725. };
  96726. /**
  96727. * Dispose the material.
  96728. * @param forceDisposeEffect Force disposal of the associated effect.
  96729. * @param forceDisposeTextures Force disposal of the associated textures.
  96730. */
  96731. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96732. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96733. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96734. if (forceDisposeTextures) {
  96735. if (this.diffuseTexture) {
  96736. this.diffuseTexture.dispose();
  96737. }
  96738. if (this.reflectionTexture) {
  96739. this.reflectionTexture.dispose();
  96740. }
  96741. }
  96742. this._renderTargets.dispose();
  96743. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96744. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96745. }
  96746. _super.prototype.dispose.call(this, forceDisposeEffect);
  96747. };
  96748. /**
  96749. * Clones the material.
  96750. * @param name The cloned name.
  96751. * @returns The cloned material.
  96752. */
  96753. BackgroundMaterial.prototype.clone = function (name) {
  96754. var _this = this;
  96755. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96756. };
  96757. /**
  96758. * Serializes the current material to its JSON representation.
  96759. * @returns The JSON representation.
  96760. */
  96761. BackgroundMaterial.prototype.serialize = function () {
  96762. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96763. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96764. return serializationObject;
  96765. };
  96766. /**
  96767. * Gets the class name of the material
  96768. * @returns "BackgroundMaterial"
  96769. */
  96770. BackgroundMaterial.prototype.getClassName = function () {
  96771. return "BackgroundMaterial";
  96772. };
  96773. /**
  96774. * Parse a JSON input to create back a background material.
  96775. * @param source The JSON data to parse
  96776. * @param scene The scene to create the parsed material in
  96777. * @param rootUrl The root url of the assets the material depends upon
  96778. * @returns the instantiated BackgroundMaterial.
  96779. */
  96780. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96781. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96782. };
  96783. /**
  96784. * Standard reflectance value at parallel view angle.
  96785. */
  96786. BackgroundMaterial.StandardReflectance0 = 0.05;
  96787. /**
  96788. * Standard reflectance value at grazing angle.
  96789. */
  96790. BackgroundMaterial.StandardReflectance90 = 0.5;
  96791. __decorate([
  96792. BABYLON.serializeAsColor3()
  96793. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96794. __decorate([
  96795. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96796. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96797. __decorate([
  96798. BABYLON.serializeAsColor3()
  96799. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96800. __decorate([
  96801. BABYLON.serialize()
  96802. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96803. __decorate([
  96804. BABYLON.serialize()
  96805. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96806. __decorate([
  96807. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96808. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96809. __decorate([
  96810. BABYLON.serializeAsTexture()
  96811. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96812. __decorate([
  96813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96814. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96815. __decorate([
  96816. BABYLON.serialize()
  96817. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96818. __decorate([
  96819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96820. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96821. __decorate([
  96822. BABYLON.serializeAsTexture()
  96823. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96824. __decorate([
  96825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96826. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96827. __decorate([
  96828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96829. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96830. __decorate([
  96831. BABYLON.serialize()
  96832. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96833. __decorate([
  96834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96835. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96836. __decorate([
  96837. BABYLON.serializeAsVector3()
  96838. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96839. __decorate([
  96840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96841. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96842. __decorate([
  96843. BABYLON.serialize()
  96844. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96845. __decorate([
  96846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96847. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96848. __decorate([
  96849. BABYLON.serialize()
  96850. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96851. __decorate([
  96852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96853. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96854. __decorate([
  96855. BABYLON.serialize()
  96856. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96857. __decorate([
  96858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96859. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96860. __decorate([
  96861. BABYLON.serialize()
  96862. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96863. __decorate([
  96864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96865. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96866. __decorate([
  96867. BABYLON.serialize()
  96868. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96869. __decorate([
  96870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96871. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96872. __decorate([
  96873. BABYLON.serialize()
  96874. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96875. __decorate([
  96876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96877. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96878. __decorate([
  96879. BABYLON.serialize()
  96880. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96881. __decorate([
  96882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96883. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96884. __decorate([
  96885. BABYLON.serialize()
  96886. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96887. __decorate([
  96888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96889. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96890. __decorate([
  96891. BABYLON.serialize()
  96892. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96893. __decorate([
  96894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96895. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96896. __decorate([
  96897. BABYLON.serializeAsImageProcessingConfiguration()
  96898. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96899. return BackgroundMaterial;
  96900. }(BABYLON.PushMaterial));
  96901. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96902. })(BABYLON || (BABYLON = {}));
  96903. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96904. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96905. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96906. s = arguments[i];
  96907. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96908. t[p] = s[p];
  96909. }
  96910. return t;
  96911. };
  96912. var BABYLON;
  96913. (function (BABYLON) {
  96914. /**
  96915. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96916. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96917. * It also helps with the default setup of your imageProcessing configuration.
  96918. */
  96919. var EnvironmentHelper = /** @class */ (function () {
  96920. /**
  96921. * constructor
  96922. * @param options
  96923. * @param scene The scene to add the material to
  96924. */
  96925. function EnvironmentHelper(options, scene) {
  96926. var _this = this;
  96927. this._errorHandler = function (message, exception) {
  96928. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96929. };
  96930. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96931. this._scene = scene;
  96932. this.onErrorObservable = new BABYLON.Observable();
  96933. this._setupBackground();
  96934. this._setupImageProcessing();
  96935. }
  96936. /**
  96937. * Creates the default options for the helper.
  96938. */
  96939. EnvironmentHelper._getDefaultOptions = function () {
  96940. return {
  96941. createGround: true,
  96942. groundSize: 15,
  96943. groundTexture: this._groundTextureCDNUrl,
  96944. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96945. groundOpacity: 0.9,
  96946. enableGroundShadow: true,
  96947. groundShadowLevel: 0.5,
  96948. enableGroundMirror: false,
  96949. groundMirrorSizeRatio: 0.3,
  96950. groundMirrorBlurKernel: 64,
  96951. groundMirrorAmount: 1,
  96952. groundMirrorFresnelWeight: 1,
  96953. groundMirrorFallOffDistance: 0,
  96954. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  96955. groundYBias: 0.00001,
  96956. createSkybox: true,
  96957. skyboxSize: 20,
  96958. skyboxTexture: this._skyboxTextureCDNUrl,
  96959. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96960. backgroundYRotation: 0,
  96961. sizeAuto: true,
  96962. rootPosition: BABYLON.Vector3.Zero(),
  96963. setupImageProcessing: true,
  96964. environmentTexture: this._environmentTextureCDNUrl,
  96965. cameraExposure: 0.8,
  96966. cameraContrast: 1.2,
  96967. toneMappingEnabled: true,
  96968. };
  96969. };
  96970. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  96971. /**
  96972. * Gets the root mesh created by the helper.
  96973. */
  96974. get: function () {
  96975. return this._rootMesh;
  96976. },
  96977. enumerable: true,
  96978. configurable: true
  96979. });
  96980. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  96981. /**
  96982. * Gets the skybox created by the helper.
  96983. */
  96984. get: function () {
  96985. return this._skybox;
  96986. },
  96987. enumerable: true,
  96988. configurable: true
  96989. });
  96990. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  96991. /**
  96992. * Gets the skybox texture created by the helper.
  96993. */
  96994. get: function () {
  96995. return this._skyboxTexture;
  96996. },
  96997. enumerable: true,
  96998. configurable: true
  96999. });
  97000. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97001. /**
  97002. * Gets the skybox material created by the helper.
  97003. */
  97004. get: function () {
  97005. return this._skyboxMaterial;
  97006. },
  97007. enumerable: true,
  97008. configurable: true
  97009. });
  97010. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97011. /**
  97012. * Gets the ground mesh created by the helper.
  97013. */
  97014. get: function () {
  97015. return this._ground;
  97016. },
  97017. enumerable: true,
  97018. configurable: true
  97019. });
  97020. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97021. /**
  97022. * Gets the ground texture created by the helper.
  97023. */
  97024. get: function () {
  97025. return this._groundTexture;
  97026. },
  97027. enumerable: true,
  97028. configurable: true
  97029. });
  97030. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97031. /**
  97032. * Gets the ground mirror created by the helper.
  97033. */
  97034. get: function () {
  97035. return this._groundMirror;
  97036. },
  97037. enumerable: true,
  97038. configurable: true
  97039. });
  97040. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97041. /**
  97042. * Gets the ground mirror render list to helps pushing the meshes
  97043. * you wish in the ground reflection.
  97044. */
  97045. get: function () {
  97046. if (this._groundMirror) {
  97047. return this._groundMirror.renderList;
  97048. }
  97049. return null;
  97050. },
  97051. enumerable: true,
  97052. configurable: true
  97053. });
  97054. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97055. /**
  97056. * Gets the ground material created by the helper.
  97057. */
  97058. get: function () {
  97059. return this._groundMaterial;
  97060. },
  97061. enumerable: true,
  97062. configurable: true
  97063. });
  97064. /**
  97065. * Updates the background according to the new options
  97066. * @param options
  97067. */
  97068. EnvironmentHelper.prototype.updateOptions = function (options) {
  97069. var newOptions = __assign({}, this._options, options);
  97070. if (this._ground && !newOptions.createGround) {
  97071. this._ground.dispose();
  97072. this._ground = null;
  97073. }
  97074. if (this._groundMaterial && !newOptions.createGround) {
  97075. this._groundMaterial.dispose();
  97076. this._groundMaterial = null;
  97077. }
  97078. if (this._groundTexture) {
  97079. if (this._options.groundTexture != newOptions.groundTexture) {
  97080. this._groundTexture.dispose();
  97081. this._groundTexture = null;
  97082. }
  97083. }
  97084. if (this._skybox && !newOptions.createSkybox) {
  97085. this._skybox.dispose();
  97086. this._skybox = null;
  97087. }
  97088. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97089. this._skyboxMaterial.dispose();
  97090. this._skyboxMaterial = null;
  97091. }
  97092. if (this._skyboxTexture) {
  97093. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97094. this._skyboxTexture.dispose();
  97095. this._skyboxTexture = null;
  97096. }
  97097. }
  97098. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97099. this._groundMirror.dispose();
  97100. this._groundMirror = null;
  97101. }
  97102. if (this._scene.environmentTexture) {
  97103. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97104. this._scene.environmentTexture.dispose();
  97105. }
  97106. }
  97107. this._options = newOptions;
  97108. this._setupBackground();
  97109. this._setupImageProcessing();
  97110. };
  97111. /**
  97112. * Sets the primary color of all the available elements.
  97113. * @param color the main color to affect to the ground and the background
  97114. */
  97115. EnvironmentHelper.prototype.setMainColor = function (color) {
  97116. if (this.groundMaterial) {
  97117. this.groundMaterial.primaryColor = color;
  97118. }
  97119. if (this.skyboxMaterial) {
  97120. this.skyboxMaterial.primaryColor = color;
  97121. }
  97122. if (this.groundMirror) {
  97123. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97124. }
  97125. };
  97126. /**
  97127. * Setup the image processing according to the specified options.
  97128. */
  97129. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97130. if (this._options.setupImageProcessing) {
  97131. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97132. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97133. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97134. this._setupEnvironmentTexture();
  97135. }
  97136. };
  97137. /**
  97138. * Setup the environment texture according to the specified options.
  97139. */
  97140. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97141. if (this._scene.environmentTexture) {
  97142. return;
  97143. }
  97144. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97145. this._scene.environmentTexture = this._options.environmentTexture;
  97146. return;
  97147. }
  97148. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97149. this._scene.environmentTexture = environmentTexture;
  97150. };
  97151. /**
  97152. * Setup the background according to the specified options.
  97153. */
  97154. EnvironmentHelper.prototype._setupBackground = function () {
  97155. if (!this._rootMesh) {
  97156. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97157. }
  97158. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97159. var sceneSize = this._getSceneSize();
  97160. if (this._options.createGround) {
  97161. this._setupGround(sceneSize);
  97162. this._setupGroundMaterial();
  97163. this._setupGroundDiffuseTexture();
  97164. if (this._options.enableGroundMirror) {
  97165. this._setupGroundMirrorTexture(sceneSize);
  97166. }
  97167. this._setupMirrorInGroundMaterial();
  97168. }
  97169. if (this._options.createSkybox) {
  97170. this._setupSkybox(sceneSize);
  97171. this._setupSkyboxMaterial();
  97172. this._setupSkyboxReflectionTexture();
  97173. }
  97174. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97175. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97176. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97177. };
  97178. /**
  97179. * Get the scene sizes according to the setup.
  97180. */
  97181. EnvironmentHelper.prototype._getSceneSize = function () {
  97182. var _this = this;
  97183. var groundSize = this._options.groundSize;
  97184. var skyboxSize = this._options.skyboxSize;
  97185. var rootPosition = this._options.rootPosition;
  97186. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97187. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97188. }
  97189. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97190. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97191. });
  97192. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97193. if (this._options.sizeAuto) {
  97194. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97195. this._scene.activeCamera.upperRadiusLimit) {
  97196. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97197. skyboxSize = groundSize;
  97198. }
  97199. var sceneDiagonalLenght = sceneDiagonal.length();
  97200. if (sceneDiagonalLenght > groundSize) {
  97201. groundSize = sceneDiagonalLenght * 2;
  97202. skyboxSize = groundSize;
  97203. }
  97204. // 10 % bigger.
  97205. groundSize *= 1.1;
  97206. skyboxSize *= 1.5;
  97207. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97208. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97209. }
  97210. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97211. };
  97212. /**
  97213. * Setup the ground according to the specified options.
  97214. */
  97215. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97216. var _this = this;
  97217. if (!this._ground) {
  97218. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97219. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97220. this._ground.parent = this._rootMesh;
  97221. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97222. }
  97223. this._ground.receiveShadows = this._options.enableGroundShadow;
  97224. };
  97225. /**
  97226. * Setup the ground material according to the specified options.
  97227. */
  97228. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97229. if (!this._groundMaterial) {
  97230. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97231. }
  97232. this._groundMaterial.alpha = this._options.groundOpacity;
  97233. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97234. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97235. this._groundMaterial.primaryColor = this._options.groundColor;
  97236. this._groundMaterial.useRGBColor = false;
  97237. this._groundMaterial.enableNoise = true;
  97238. if (this._ground) {
  97239. this._ground.material = this._groundMaterial;
  97240. }
  97241. };
  97242. /**
  97243. * Setup the ground diffuse texture according to the specified options.
  97244. */
  97245. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97246. if (!this._groundMaterial) {
  97247. return;
  97248. }
  97249. if (this._groundTexture) {
  97250. return;
  97251. }
  97252. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97253. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97254. return;
  97255. }
  97256. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97257. diffuseTexture.gammaSpace = false;
  97258. diffuseTexture.hasAlpha = true;
  97259. this._groundMaterial.diffuseTexture = diffuseTexture;
  97260. };
  97261. /**
  97262. * Setup the ground mirror texture according to the specified options.
  97263. */
  97264. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97265. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97266. if (!this._groundMirror) {
  97267. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97268. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97269. this._groundMirror.anisotropicFilteringLevel = 1;
  97270. this._groundMirror.wrapU = wrapping;
  97271. this._groundMirror.wrapV = wrapping;
  97272. this._groundMirror.gammaSpace = false;
  97273. if (this._groundMirror.renderList) {
  97274. for (var i = 0; i < this._scene.meshes.length; i++) {
  97275. var mesh = this._scene.meshes[i];
  97276. if (mesh !== this._ground &&
  97277. mesh !== this._skybox &&
  97278. mesh !== this._rootMesh) {
  97279. this._groundMirror.renderList.push(mesh);
  97280. }
  97281. }
  97282. }
  97283. }
  97284. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97285. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97286. };
  97287. /**
  97288. * Setup the ground to receive the mirror texture.
  97289. */
  97290. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97291. if (this._groundMaterial) {
  97292. this._groundMaterial.reflectionTexture = this._groundMirror;
  97293. this._groundMaterial.reflectionFresnel = true;
  97294. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97295. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97296. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97297. }
  97298. };
  97299. /**
  97300. * Setup the skybox according to the specified options.
  97301. */
  97302. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97303. var _this = this;
  97304. if (!this._skybox) {
  97305. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97306. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97307. }
  97308. this._skybox.parent = this._rootMesh;
  97309. };
  97310. /**
  97311. * Setup the skybox material according to the specified options.
  97312. */
  97313. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97314. if (!this._skybox) {
  97315. return;
  97316. }
  97317. if (!this._skyboxMaterial) {
  97318. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97319. }
  97320. this._skyboxMaterial.useRGBColor = false;
  97321. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97322. this._skyboxMaterial.enableNoise = true;
  97323. this._skybox.material = this._skyboxMaterial;
  97324. };
  97325. /**
  97326. * Setup the skybox reflection texture according to the specified options.
  97327. */
  97328. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97329. if (!this._skyboxMaterial) {
  97330. return;
  97331. }
  97332. if (this._skyboxTexture) {
  97333. return;
  97334. }
  97335. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97336. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97337. return;
  97338. }
  97339. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97340. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97341. this._skyboxTexture.gammaSpace = false;
  97342. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97343. };
  97344. /**
  97345. * Dispose all the elements created by the Helper.
  97346. */
  97347. EnvironmentHelper.prototype.dispose = function () {
  97348. if (this._groundMaterial) {
  97349. this._groundMaterial.dispose(true, true);
  97350. }
  97351. if (this._skyboxMaterial) {
  97352. this._skyboxMaterial.dispose(true, true);
  97353. }
  97354. this._rootMesh.dispose(false);
  97355. };
  97356. /**
  97357. * Default ground texture URL.
  97358. */
  97359. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97360. /**
  97361. * Default skybox texture URL.
  97362. */
  97363. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97364. /**
  97365. * Default environment texture URL.
  97366. */
  97367. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97368. return EnvironmentHelper;
  97369. }());
  97370. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97371. })(BABYLON || (BABYLON = {}));
  97372. //# sourceMappingURL=babylon.environmentHelper.js.map
  97373. var BABYLON;
  97374. (function (BABYLON) {
  97375. /**
  97376. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97377. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97378. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97379. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97380. */
  97381. var VideoDome = /** @class */ (function (_super) {
  97382. __extends(VideoDome, _super);
  97383. /**
  97384. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97385. * @param name Element's name, child elements will append suffixes for their own names.
  97386. * @param urlsOrVideo
  97387. * @param options An object containing optional or exposed sub element properties:
  97388. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97389. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97390. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97391. * @param options **loop=true** Automatically loop video on end.
  97392. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97393. */
  97394. function VideoDome(name, urlsOrVideo, options, scene) {
  97395. var _this = _super.call(this, name, scene) || this;
  97396. // set defaults and manage values
  97397. name = name || "videoDome";
  97398. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97399. options.clickToPlay = Boolean(options.clickToPlay);
  97400. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97401. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97402. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97403. // create
  97404. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97405. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97406. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97407. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97408. flat: false,
  97409. radius: options.size,
  97410. subdivisions: options.resolution,
  97411. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97412. }, scene);
  97413. // configure material
  97414. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97415. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97416. material.reflectionTexture = _this._videoTexture;
  97417. material.useEquirectangularFOV = true;
  97418. material.fovMultiplier = 1.0;
  97419. // configure mesh
  97420. _this._mesh.material = material;
  97421. _this._mesh.parent = _this;
  97422. // optional configuration
  97423. if (options.clickToPlay) {
  97424. scene.onPointerUp = function () {
  97425. _this._videoTexture.video.play();
  97426. };
  97427. }
  97428. return _this;
  97429. }
  97430. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97431. /**
  97432. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97433. * Also see the options.resolution property.
  97434. */
  97435. get: function () {
  97436. return this._material.fovMultiplier;
  97437. },
  97438. set: function (value) {
  97439. this._material.fovMultiplier = value;
  97440. },
  97441. enumerable: true,
  97442. configurable: true
  97443. });
  97444. /**
  97445. * Releases resources associated with this node.
  97446. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97447. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97448. */
  97449. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97450. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97451. this._videoTexture.dispose();
  97452. this._mesh.dispose();
  97453. this._material.dispose();
  97454. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97455. };
  97456. return VideoDome;
  97457. }(BABYLON.Node));
  97458. BABYLON.VideoDome = VideoDome;
  97459. })(BABYLON || (BABYLON = {}));
  97460. //# sourceMappingURL=babylon.videoDome.js.map
  97461. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  97462. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  97463. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97464. globalObject["BABYLON"] = BABYLON;
  97465. //backwards compatibility
  97466. if(typeof earcut !== 'undefined') {
  97467. globalObject["Earcut"] = {
  97468. earcut: earcut
  97469. };
  97470. }
  97471. return BABYLON;
  97472. });